from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
import datetime
from .forms import *
from BasicData.models import *

# Create your views here.


# Register
def register(request):
    form = CandidatAddForm()
    if request.method == 'POST':
        form = CandidatAddForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            nom = cd.get('nom').upper()
            prenoms = cd.get('prenoms').upper()
            email = cd.get('email').lower()
            password = cd.get('password').replace(" ","")
            password2 = cd.get('password2').replace(" ","")

            # ON RECUPERE LES MAILS
            mails = User.objects.filter(email=email)

            # GESTION DES CONTRAINTES
            if password != password2:
                messages.error(request, 'Les mots de passe ne sont pas identiques')
            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 '/' ")
            elif mails:
                messages.error(request, "Ce mail n'est pas disponible")
            else:
                etudiant = Etudiant.objects.create(
                    nom = nom,
                    prenoms = prenoms,
                    email = email,
                    actif =False
                )
                etudiant.set_password(password)
                etudiant.save()

                messages.success(request, 'Félicitations! Votre compte à été créé. Connectez-vous pour continuer')
                form = CandidatAddForm()
                return redirect('/scolarite/ins_login/')
        else:
            messages.error(request, 'Données non valide, verifiez les svp!')
    else:
        form = CandidatAddForm()

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


def ins_login(request):

    if request.method == "POST":
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            # Redirect to a success page.
            try:
                Etudiant.objects.get(email=user.email,actif =False)
                return redirect("Scolarite:inscription_profile_home")
            except Etudiant.DoesNotExist:
                messages.error(request,'Accès interdit')
        else:
            messages.error(request, 'Vérifiez les champs svp')
    return render(request,'preinscription/login.html')

# Logout
def ins_logout(request):
    logout(request)
    return redirect('Scolarite:ins_login')




def preinscription_home(request):
    return render(request,'preinscription/base.html')


@login_required(login_url='Solarite:ins_login')
def inscription_profile_home(request):
    etudiant =  Etudiant.objects.get(email=request.user.email)
    context={
        'etudiant':etudiant,
    }
    return render(request,'preinscription/profil/profil_home.html',context)


@login_required(login_url='Solarite:ins_login')
def edit_profil(request,id):
    # ON RECUPERE LES INFOS DU CANDIDAT
    etudiant = Etudiant.objects.get(id=id)

    form = EtudiantEditForm(instance=etudiant)
    hide_form = False

    if request.method == 'POST':
        form = EtudiantEditForm(request.POST, instance=etudiant)
        if form.is_valid():
            form.save()
            messages.success(request, 'Votre profil a bien été modifié')
            return redirect('Scolarite:inscription_profile_home')
            #hide_form =True
        else:
            messages.error(request, 'Erreur! vérifiez les champs svp.')

    context={
        'etudiant':etudiant,
        'form': form,
        'hide_form': hide_form,
    }
    return render(request,'preinscription/profil/profil_edit.html',context)


@login_required(login_url='Solarite:ins_login')
def add_photo(request):
    # ON RECUPERE LES INFOS DU CANDIDAT
    etudiant = Etudiant.objects.get(email=request.user.email)
    print(etudiant.avatar.url)

    form = PhotoAddForm(request.POST, request.FILES, instance=etudiant)
    if request.method == 'POST':
        form = PhotoAddForm(request.POST, request.FILES, instance=etudiant)
        if form.is_valid():
            form.save()
            messages.success(request, "Photo ajoutée")
            return redirect('Scolarite:add_photo')
        else:
            messages.error(request, 'Erreur! vérifiez les champs svp.')

    context={
        'etudiant':etudiant,
        'form':form,
    }
    return render(request,'preinscription/profil/add_photo.html',context)