from django.core.mail import send_mail
from django.shortcuts import render, redirect
from BasicData.models import User
from .forms import *
from django.contrib import messages

from django.http import HttpResponse, BadHeaderError
from django.contrib.auth.forms import PasswordResetForm
# from django.contrib.auth.models import User
from django.template.loader import render_to_string
from django.db.models.query_utils import Q
from django.utils.http import urlsafe_base64_encode
from django.contrib.auth.tokens import default_token_generator
from django.utils.encoding import force_bytes
from usp_pedagogie.settings import EMAIL_HOST_USER
from django.contrib.sites.shortcuts import get_current_site


def check_account(request):
    form = UserCheckForm()
    if request.method == 'POST':
        form = UserCheckForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            username = cd.get('username')
            secret = cd.get('secret')

            # ON RECUPERE LE COMPTE
            try:
                user = User.objects.get(email=username)
            except User.DoesNotExist:
                user = None

            if user:
                if user.id == secret:
                    return redirect('/renew_password/' + str(secret) + '/')
                else:
                    messages.error(request, 'Mauvais code secret')
            else:
                messages.error(request, "Ce compte n'existe pas")

    context = {
        'form': form
    }
    return render(request, 'password/check_account.html', context)


def renew_password(request, id):
    # ON RECUPERE LE COMPTE
    user = User.objects.get(id=id)

    form = UserRenewPasswordForm()
    if request.method == 'POST':
        form = UserRenewPasswordForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            password = cd.get('password')
            password2 = cd.get('password2')

            # GESTION DES CONTRAINTES
            if password != password2:
                messages.error(request, 'Les mots de passe sont différents')
            elif len(password) < 8:
                messages.error(request, 'Le mot de passe doit être au moins 8 caractères')
            elif '/' in password:
                messages.error(request, "Le mot de passe ne doit pas contenir de '/' ")
            else:
                user.set_password(password)
                user.save()
                return redirect('/renew_done/')

    context = {
        'form': form,
        'user': user,
    }
    return render(request, 'password/renew_password.html', context)


def renew_done(request):
    return render(request, 'password/renew_done.html')


################### PASSWORD RESET #####################

def password_reset_request(request):
    if request.method == "POST":
        password_reset_form = PasswordResetForm(request.POST)
        if password_reset_form.is_valid():
            data = password_reset_form.cleaned_data['email']
            associated_users = User.objects.filter(Q(email=data))
            if associated_users.exists():
                for user in associated_users:
                    subject = "Réinitialisation du mot de passe"
                    email_template_name = "password/password_reset_email.txt"
                    current_site = get_current_site(request)
                    c = {
                        "email": user.email,
                        'domain': current_site.domain,
                        'site_name': 'Website',
                        "uid": urlsafe_base64_encode(force_bytes(user.pk)),
                        "user": user,
                        'token': default_token_generator.make_token(user),
                        'protocol': 'http',
                    }
                    email = render_to_string(email_template_name, c)
                    try:
                        send_mail(subject, email, EMAIL_HOST_USER, [user.email], fail_silently=False)
                    except BadHeaderError:
                        return HttpResponse('Invalid header found.')
                    return redirect("/password_reset/done/")
    password_reset_form = PasswordResetForm()
    return render(request=request, template_name="password/password_reset.html",
                  context={"password_reset_form": password_reset_form})

########################################################
