from django.contrib import messages
from django.contrib.auth import login
from django.contrib.auth.models import User
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.shortcuts import get_current_site
from django.shortcuts import redirect, render
from django.template.loader import render_to_string
from django.utils.encoding import force_bytes, force_str
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.core.mail import EmailMessage
from bigsansar.contrib.account.forms import SignUpForm


def signup(request):
    if request.user.is_authenticated:
        return redirect('/dashboard')
    else:
        if request.method == 'POST':
            form = SignUpForm(request.POST)
            if form.is_valid():
                user = form.save(commit=False)
                user.is_active = False
                user.save()

                # send mail for varification
                current_site = get_current_site(request)
                mail_subject = 'Activate your account.'
                message = render_to_string('acc_active_email.html', {
                    'user': user,
                    'domain': current_site.domain,
                    'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                    'token': default_token_generator.make_token(user),
                })
                to_email = form.cleaned_data.get('email')
                email = EmailMessage(
                    mail_subject, message, to=[to_email]
                )
                email.send()

                messages.success(request, 'Sing Up Successfully.Please verify your email address access to admin panel.')
                return redirect('/dashboard')
        else:
            form = SignUpForm()
        return render(request, 'signup.html', {'form': form})


def active(request, uidb64, token):
    try:
        uid = force_str(urlsafe_base64_decode(uidb64))
        user = User.objects.get(pk=uid)
        ch_token = default_token_generator.check_token(user, token)

    except(TypeError, ValueError, OverflowError, User.DoesNotExist):
        messages.warning(request, 'user not found')
        return redirect('/dashboard')

    if user is not None:
        if ch_token:
            user.is_active = True
            user.save()
            login(request, user)
            messages.success(request, 'Thank you for your email confirmation. Now you can login your account.')
            return redirect('/dashboard')
        else:
            messages.warning(request, 'Activation link is invalid!')
            return redirect('/dashboard')