from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from BasicData.models import *
from .forms import *
from BasicData.custom_fonctions import *
from django.contrib import messages
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth.hashers import make_password
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from BasicData.custom_fonctions import *
from BasicData.templatetags.custom_tag import get_credit_ue, get_etudiant_moyenne_ue2

@login_required(login_url='BasicData:login')
def vice_president_home(request):
    # ROLE
    user = Enseignant.objects.get(email=request.user.email)

    # LISTE DES UFRS
    UFRS= Ufr.objects.all().order_by('libelle')

    context={
        'user': user,
        'UFRS':UFRS,
        'AnUniv':Annee.objects.last()
    }
    return render(request,'vice_president/vpr_home.html',context)


@login_required(login_url='BasicData:login')
def vpr_ufr_home(request,id):
    # ROLE
    user = Enseignant.objects.get(email=request.user.email)

    # INFOS UFR
    UFR = Ufr.objects.get(id=id)
    context={
        'user':user,
        'UFR':UFR,
        'AnUniv': Annee.objects.last()
    }
    return render(request,'vice_president/vpr_ufr_home.html',context)


@login_required(login_url='BasicData:login')
def vpr_ue(request,id):
    # ROLE
    user = Enseignant.objects.get(email=request.user.email)

    # On recupere l'UFR et les UE
    UFR = Ufr.objects.get(id=id)
    UE = Ue.objects.filter(ufr=UFR,active=True).order_by('libelle')

    # ON RECUPERE LES ANNEES ET LES NIVEAUX
    annees = Annee.objects.all().order_by('-id')
    niveaux = Niveau.objects.all()
    anUniv = Annee.objects.last()
    niveau = Niveau.objects.first().id

    # FILTRE FORM
    formFil = PvFilterForm()
    if request.method == 'POST':
        if 'AnneeFilter' in request.POST:
            formFil = PvFilterForm(request.POST)
            if formFil.is_valid():
                cd = formFil.cleaned_data
                anUniv = Annee.objects.get(id=cd.get('annee'))
                niveau = cd.get('niveau')


    #UES = [Ue.objects.get(id=ue['ue__id']) for ue in ParcoursSemestreUe.objects.filter(ue__niveau__id=niveau, parcoursSemestre__gradeMentionUfr__ufr=UFR).values('ue__id').distinct().order_by('ue__libelle')]
    #UES = Ue.objects.filter(ufr=UFR,)
    semestres = [Semestre.objects.get(id=sem['semestre']) for sem in Ue.objects.filter(ufr=UFR,niveau__id=niveau, active=True).values('semestre').distinct().order_by('semestre')]

    context = {
        'user': user,
        'UFR': UFR,
        'anUniv': anUniv,
        'annees': annees,
        'niveaux': niveaux,
        'niveau': Niveau.objects.get(id=niveau),
        'formFil': formFil,
        'semestres': semestres,
        #'UES': UES,
    }
    return render(request, 'vice_president/vpr_liste_ue.html', context)


@login_required(login_url='BasicData:login')
def vpr_ecue(request,id):
    # ROLE
    user = Enseignant.objects.get(email=request.user.email)

    # On recupere l'UFR et les UCUES
    UFR = Ufr.objects.get(id=id)
    ECUE = Ecue.objects.filter(ue__ufr=UFR,active=True).order_by('libelle')

    # ON recupere la derniere Année
    annee_univ = Annee.objects.last()

    # ON RECUPERE LES ANNEES ET LES NIVEAUX
    annees = Annee.objects.all().order_by('-id')
    niveaux = Niveau.objects.all()
    anUniv = Annee.objects.last()
    niveau = Niveau.objects.first().id

    # FILTRE FORM
    formFil = PvFilterForm()
    if request.method == 'POST':
        if 'AnneeFilter' in request.POST:
            formFil = PvFilterForm(request.POST)
            if formFil.is_valid():
                cd = formFil.cleaned_data
                anUniv = Annee.objects.get(id=cd.get('annee'))
                niveau = cd.get('niveau')

    semestres = [Semestre.objects.get(id=sem['ue__semestre']) for sem in
                 Ecue.objects.filter(ue__ufr=UFR, ue__niveau__id=niveau, ue__active=True).values('ue__semestre').distinct().order_by(
                     'ue__semestre')]
    context = {
        'user': user,
        'UFR': UFR,
        'semestres': semestres,
        #'ECUES': ECUESLIST,
        'anUniv': anUniv,
        'annees': annees,
        'niveaux': niveaux,
        'niveau': Niveau.objects.get(id=niveau),
        'formFil': formFil,
    }
    return render(request, 'vice_president/vpr_liste_ecue.html', context)


@login_required(login_url='BasicData:login')
def vpr_pv_view(request,id):
    user = Enseignant.objects.get(email=request.user.email)

    # On recupere l'enseignant
    enseignant = Enseignant.objects.get(email=request.user.email)

    # ON RECUPERE L'UFR
    UFR = Ufr.objects.get(id=id)
    ############################################

    # ON RECUPERE LES ANNEES/NIVEAUX/SEMESTRES
    annees = Annee.objects.all().order_by('-id')
    niveaux = Niveau.objects.all()
    semestres = Semestre.objects.all()

    # ON RECUPERE LES DONNEES DU FORMULAIRE
    get_annee = []
    get_niveau = []
    get_semestre = []
    form = PvFilterForm()
    if request.method == 'POST':
        form = PvFilterForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            annee = cd.get('annee')
            niveau = cd.get('niveau')
            semestre = cd.get('semestre')

            # ON RECUPERE LES INFOS
            get_annee = Annee.objects.get(id=annee)
            get_niveau = Niveau.objects.get(id=niveau)
            get_semestre = Semestre.objects.get(id=semestre)

    context = {
        'user': user,
        'form': form,
        'annees': annees,
        'UFR': UFR,
        'niveaux': niveaux,
        'semestres': semestres,
        'get_annee': get_annee,
        'get_niveau': get_niveau,
        'get_semestre': get_semestre,
    }
    return render(request, 'vice_president/vpr_pv_home.html', context)

@login_required(login_url='BasicData:login')
def vpr_etudiant_list(request,id):
    # ROLE
    user = Enseignant.objects.get(email=request.user.email)

    # ON RECUPERE L'UFR ET L'ANNEE
    UFR = Ufr.objects.get(id=id)
    anUniv=Annee.objects.last()

    # ON RECUPERE LES ANNEES ET LES NIVEAUX
    annees = Annee.objects.all().order_by('-id')
    niveaux = Niveau.objects.all()

    niveau = 1
    formFil = PvFilterForm()
    if request.method == 'POST':
        if 'AnneeFilter' in request.POST:
            formFil = PvFilterForm(request.POST)
            if formFil.is_valid():
                cd = formFil.cleaned_data
                anUniv = Annee.objects.get(id=cd.get('annee'))
                niveau = cd.get('niveau')

    # ON RECUPERE LES ETUDIANTS DE L'UFR
    etudiants = [ etudNIV.etudiant for etudNIV in NiveauEtudiant.objects.filter(annee=anUniv, etudiant__ufr=UFR,niveau__id=niveau).order_by('etudiant__nom') ]


    context={
        'user': user,
        'UFR':UFR,
        'etudiant_list':etudiants,
        'annees': annees,
        'niveaux': niveaux,
        'niveau': Niveau.objects.get(id=niveau),
        'anUniv': anUniv,
    }
    return render(request,'vice_president/vpr_etudiant_list.html',context)


@login_required(login_url='BasicData:login')
def vpr_etudiant_ue(request,id,an):
    # ROLE
    user = enseignant = Enseignant.objects.get(email=request.user.email)

    AnUniv = Annee.objects.get(id=an)

    # On recupere ls UEs de l'etudiant
    etudiant = Etudiant.objects.get(id=id)

    # ON RECUPERE LE NIVEAU DE L'ETUDIANT
    nivEtud = NiveauEtudiant.objects.filter(annee=AnUniv, etudiant=etudiant).last()
    semestres = None
    if nivEtud:
        semestres = Semestre.objects.filter(niveau=nivEtud.niveau).order_by('libelle')



    context = {
        'user': user,
        'enseignant': enseignant,
        'an': an,
        'etudiant': etudiant,
        'semestres': semestres,
        'EtudAn': [etudiant, AnUniv],
        'UfrAn': [etudiant.ufr.id, AnUniv.id],
        'UFR': etudiant.ufr,
        'AnUniv': AnUniv,
        'annee': AnUniv,
        'niveau': nivEtud.niveau,
        'annees': Annee.objects.all().order_by('-id'),
    }
    return render(request,'vice_president/vpr_etudiant_ue.html',context)


@login_required(login_url='BasicData:login')
def vpr_etudiant_detail_ue(request,ue,id,an):
    # ROLE
    try:
        user = Enseignant.objects.get(email=request.user.email)
    except Enseignant.DoesNotExist:
        user = None

    #annee = Annee.objects.get(id=an)

    # On recupere toute les Ecues de l'Ue
    ecues = Ecue.objects.filter(ue__id=ue,active=True)
    # On recupere l'etudiant
    etudiant = Etudiant.objects.get(id=id)

    # On recupere l'etudiant
    # etudiant = Etudiant.objects.get(email=request.user.email)
    NivEtud = NiveauEtudiant.objects.filter(annee__id=an, etudiant=etudiant).last()
    niveau = None
    if NivEtud:
        niveau = NivEtud.niveau
    EcueDataList = [etudiant, an]
    EX = [etudiant, an, 'ex']
    CC = [etudiant, an, 'cc']

    context = {
        'user': user,
        'an': an,
        'EX': EX,
        'CC': CC,
        'ecues': ecues,
        'etudiant': etudiant,
        'niveau': niveau,
        'EcueDataList': EcueDataList,
        'ue': Ue.objects.get(id=ue),
        'annee': Annee.objects.get(id=an),
    }
    return render(request,'EspaceEtudiant/note-detail.html',context)


@login_required(login_url='BasicData:login')
def vpr_enseignant_list(request,id):
    # ROLE
    user = Enseignant.objects.get(email=request.user.email)

    # ON RECUPERE L'UFR ET L'ANNEE
    UFR = Ufr.objects.get(id=id)

    # ON RECUPERE LES ANNEES ET LES NIVEAUX
    annees = Annee.objects.all().order_by('-id')
    niveaux = Niveau.objects.all()

    niveau = 1
    anUniv = Annee.objects.last()
    formFil = PvFilterForm()
    if request.method == 'POST':
        if 'AnneeFilter' in request.POST:
            formFil = PvFilterForm(request.POST)
            if formFil.is_valid():
                cd = formFil.cleaned_data
                anUniv = Annee.objects.get(id=cd.get('annee'))
                niveau = cd.get('niveau')

    # ON RECUPERE LES ENSEIGNANTS DE L'UFR
    enseignants = [ens.enseignant for ens in EnseignantUfr.objects.filter(ufr=UFR, annee=anUniv).order_by('enseignant__nom')]


    context={
        'user': user,
        'UFR':UFR,
        'enseignants':enseignants,
        'annees': annees,
        'niveaux': niveaux,
        'niveau': Niveau.objects.get(id=niveau),
        'anUniv': anUniv,
    }
    return render(request,'vice_president/vpr_enseignant_list.html',context)


@login_required(login_url='BasicData:login')
def vpr_manage_password(request):
    show_form = 'show'
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            cd = form.cleaned_data
            an = cd.get('old_password')
            update_session_auth_hash(request, user)  # Important!
            messages.success(request, 'Votre mot de passe a bien été modifié!')
            show_form ='hide'
        else:
            messages.error(request, 'Verifiez les champs')
    else:
        form = PasswordChangeForm(request.user)
    context = {'form':form,'show_form':show_form,'AnUniv': Annee.objects.last()}
    return render(request,'vice_president/vpr_change_password.html',context)