from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect

from BasicData.templatetags.custom_tag import get_decision_annuelle_etudiant, decision_annuelle_etudiant
from BasicData.templatetags.custom_tag_obj import get_semestre_niveau_by_annee
from .forms import *
from BasicData.models import *
from .models import *
from django.contrib import messages
from django.http import FileResponse, Http404


# Create your views here.

@login_required(login_url='BasicData:login')
def ags_home(request):
    return render(request, 'scolarite/ags_base.html')


@login_required(login_url='BasicData:login')
def ags_inscrption_list(request):
    # default
    etudiants = Etudiant.objects.filter(process=True)

    # inscrits actuels
    etudiants_ins = len(NiveauEtudiant.objects.filter(annee=Annee.objects.last()))
    etudiants_non_ins = len(Etudiant.objects.filter(actif=False))

    context = {
        'etudiants': etudiants,
        'etudiants_ins': etudiants_ins,
        'etudiants_non_ins': etudiants_non_ins,
        'annee': Annee.objects.last(),
    }
    return render(request, 'scolarite/inscription/ags_inscription_list.html', context)


@login_required(login_url='BasicData:login')
def ags_inscrits_list(request):
    # default
    etudiants = [etud.etudiant for etud in NiveauEtudiant.objects.filter(annee=Annee.objects.last())]

    context = {
        'etudiants': etudiants,
        'annee': Annee.objects.last(),
    }
    return render(request, 'scolarite/inscription/ags_inscrits_list.html', context)


@login_required(login_url='BasicData:login')
def ags_prevu_list(request):
    # default
    etudiants = Etudiant.objects.filter(actif=False)

    context = {
        'etudiants': etudiants,
        'annee': Annee.objects.last(),
    }
    return render(request, 'scolarite/inscription/ags_prevu_list.html', context)


@login_required(login_url='BasicData:login')
def preinscription_home(request):
    return render(request, 'preinscription/base.html')


@login_required(login_url='BasicData:login')
def ags_inscrption_agree(request, id):
    # ON RECUPER L'ETUDIANT
    etudiant = Etudiant.objects.get(id=id)

    # ON RECUPERE LES TYPES DE DOCUMENT
    typedocs = TypeDocument.objects.all()

    # ON VERIFIE SI L'ETUDIANT EST DEJA INSCRIT
    NT = NiveauEtudiant.objects.filter(
        etudiant=etudiant,
        niveau=Niveau.objects.get(id=1),
        annee=Annee.objects.last()
    )

    check_invalid_doc = len(Document.objects.filter(etudiant=etudiant, annee=Annee.objects.last(), valid=True))

    if request.method == 'POST':
        if 'agree' in request.POST:
            if NT:
                messages.error(request, 'Cet étudiant est déja inscrit')
            elif check_invalid_doc == 0:
                messages.error(request, "Certains document n'ont pas été validés")
            else:
                NiveauEtudiant.objects.create(
                    etudiant=etudiant,
                    niveau=Niveau.objects.get(id=1),
                    annee=Annee.objects.last()
                )
                etudiant.actif = True
                etudiant.process = False
                etudiant.save()
                messages.success(request, 'Inscription réussie')
                return redirect('/scolarite/ags_inscrption_agree/' + str(etudiant.id) + '/')

    form = DocIdForm()
    if request.method == 'POST':
        if 'valid_doc' in request.POST:
            form = DocIdForm(request.POST)
            if form.is_valid():
                cd = form.cleaned_data
                dt = cd.get('doc')
                docs = Document.objects.filter(etudiant=etudiant, annee=Annee.objects.last(), typedoc__id=dt).last()
                if docs:
                    docs.valid = True
                    docs.save()
                    messages.success(request, 'document validé')
                    return redirect('/scolarite/ags_inscrption_agree/' + str(etudiant.id) + '/')
                else:
                    messages.error(request, 'Aucun document trouvé')

    context = {
        'etudiant': etudiant,
        'typedocs': typedocs,
        'NT': NT,
        'form': form,
        'annee': Annee.objects.last(),
    }
    return render(request, 'scolarite/inscription/ags_inscription_agree.html', context)


@login_required(login_url='BasicData:login')
def doc_preview(request, id, typdoc):
    etudiant = Etudiant.objects.get(id=id)
    document = Document.objects.filter(typedoc__id=typdoc, etudiant=etudiant).last()

    context = {
        'etudiant': etudiant,
        'document': document,
    }
    return render(request, 'scolarite/inscription/doc_preview.html', context)


@login_required(login_url='BasicData:login')
def ags_reinscrption_list(request):
    # default
    #etudiants = Etudiant.objects.filter(actif=True).order_by('nom')
    etudiants = [etud.etudiant for etud in Reinscription.objects.filter(annee=Annee.objects.last())]


    context = {
        'etudiants': etudiants,
        'annee': Annee.objects.last()
    }

    return render(request, 'scolarite/reinscription/reinscription_list.html', context)


@login_required(login_url='BasicData:login')
def ags_reinscrption_check(request, id):
    # ON RECUPER L'ETUDIANT
    etudiant = Etudiant.objects.get(id=id)

    # ON RECUPERE LES TYPES DE DOCUMENT
    typedocs = TypeDocument.objects.all()

    # ON RECUPERE L'ANNEE PRECEDENTE
    annees = Annee.objects.all().order_by('-id')[:2]
    if annees and len(annees) > 1:
        annee_prec = annees[1]
    elif annees and len(annees) == 1:
        annee_prec = annees[0]
    else:
        annee_prec = None

    # ON RECUPERE LE NIVEAU DE L'ETUDIANT
    nivEtud = NiveauEtudiant.objects.filter(annee=annee_prec, etudiant=etudiant).last()
    semestres = None
    niv_actuel = None
    niv_suivant = None
    if nivEtud:
        niv_actuel = nivEtud.niveau
        # ON RECUPERE LE NIVEAU SUIVANT DE L'ETUDIANT
        niv_suivant = Niveau.objects.filter(id__gt=niv_actuel.id).first()
        semestres = Semestre.objects.filter(niveau=nivEtud.niveau).order_by('libelle')

    # DECISION ANNUELLE
    decision_annuelle = decision_annuelle_etudiant(etudiant)
    if decision_annuelle == 'AJOURNE(E)':
        niv_suivant = niv_actuel


    # ON VERIFIE SI L'ETUDIANT EST DEJA INSCRIT
    NT = NiveauEtudiant.objects.filter(
        etudiant=etudiant,
        niveau=niv_suivant,
        annee=Annee.objects.last()
    )
    check_doc = Document.objects.filter(etudiant=etudiant, annee=Annee.objects.last(), valid=False)
    check_invalid_doc = len(Document.objects.filter(etudiant=etudiant, annee=Annee.objects.last(), valid=False))


    form = ReinscAgreeForm()
    if request.method == 'POST':
        if 'agree' in request.POST:
            form = ReinscAgreeForm(request.POST)
            if form.is_valid():
                #cd = form.cleaned_data
                if NT:
                    messages.error(request, 'Cet étudiant est déja inscrit')
                #elif not check_doc:
                #    messages.error(request, 'Aucun document joint par cet étudiant')
                #elif check_doc and check_invalid_doc > 0:
                #    messages.error(request, 'Certains document ne sont pas validés')
                else:
                    NiveauEtudiant.objects.create(
                        etudiant=etudiant,
                        niveau=niv_suivant,
                        annee=Annee.objects.last()
                    )
                    etudiant.actif = True
                    etudiant.save()
                    re = Reinscription.objects.filter(annee=Annee.objects.last(),done=False).last()
                    re.done = True
                    re.save()
                    messages.success(request, 'Inscription réussie')
                    return redirect('/scolarite/ags_reinscrption_check/' + str(etudiant.id) + '/')
            else:
                messages.error(request,form.fields)

    form = DocIdForm()
    if request.method == 'POST':
        if 'valid_doc' in request.POST:
            form = DocIdForm(request.POST)
            if form.is_valid():
                cd = form.cleaned_data
                dt = cd.get('doc')
                docs = Document.objects.filter(etudiant=etudiant, annee=Annee.objects.last(), typedoc__id=dt).last()
                if docs:
                    docs.valid = True
                    docs.save()
                    messages.success(request, 'document validé')
                    return redirect('/scolarite/ags_reinscrption_check/' + str(etudiant.id) + '/')
                else:
                    messages.error(request, 'Aucun document trouvé')

    context = {
        'etudiant': etudiant,
        'typedocs': typedocs,
        'NT': NT,
        'form': form,
        'niv_suivant': niv_suivant,
        'annee': Annee.objects.last(),
        'semestres': semestres,
        'annee_prec': annee_prec,
        'UfrAn': [etudiant.ufr.id, annee_prec.id],
        'EtudAn': [etudiant, annee_prec],
    }
    return render(request, 'scolarite/reinscription/reinscription_check.html', context)


@login_required(login_url='BasicData:login')
def ags_pv_list(request):
    # LISTE DES PV
    pvs = PvArchive.objects.all().order_by('-id')

    # init DATA
    annees = Annee.objects.all().order_by('-id')
    ufrs = Ufr.objects.all()
    niveaux = Niveau.objects.all().order_by('id')

    # EXPORT FILTER FORM
    an = None
    ufr = None
    niveau = None
    form = PvArchForm()
    if request.method =='POST':
        form = PvArchForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            an = cd.get('annee')
            ufr = cd.get('ufr')
            niveau = cd.get('niveau')

            #an = Annee.objects.get(id=cd.get('annee'))
            #ufr = Ufr.objects.get(id=cd.get('ufr'))
            #niveau = Niveau.objects.get(id=cd.get('niveau'))


    context = {
        'pvs': pvs,
        'annees': annees,
        'niveaux': niveaux,
        'ufrs': ufrs,
        'an': an,
        'ufr': ufr,
        'niveau': niveau,
    }
    return render(request, 'scolarite/pv_list.html', context)


@login_required(login_url='BasicData:login')
def pdf_display(request, id):
    # ON RECUPERE LE PV
    pv = PvArchive.objects.get(id=id)
    try:
        return FileResponse(open('media/' + str(pv.document), 'rb'), content_type='application/pdf')
    except FileNotFoundError:
        raise Http404()


@login_required(login_url='BasicData:login')
def demande_list(request):
    # ON RECUPERE LES DEMANDES
    ags = AgentScolarite.objects.filter(email=request.user.email).last()
    user = Enseignant.objects.filter(email=request.user.email).last()
    ensUfr = []
    if user:
        ensUfr = [EnsU.ufr for EnsU in EnseignantUfr.objects.filter(enseignant=user)]

    if ags:
        #typList = ['Certificat de scolarité','Relevé de notes']
        typList = [tm.libelle for tm in TypeDemandeActes.objects.filter(cible__in=['scolarité', 'tout'])]
    else:
        #typList = ["Relevé de notes", "Certificat d'admission", "Attestation provisoire de réussite",
        #           "Diplôme définitif", "Parcours académique", "Certificat de suspension"]

        typList = [tm.libelle for tm in TypeDemandeActes.objects.filter(cible__in=['ufr','tout'])]

    annees = Annee.objects.all().order_by('-id')
    typeDemandes = TypeDemandeActes.objects.filter(libelle__in=typList)
    if ags:
        demandes = DemandeActes.objects.filter(type_demande__libelle__in=typList,reception=False).order_by('-id')
    else:
        demandes = DemandeActes.objects.filter(type_demande__libelle__in=typList,etudiant__ufr__in=ensUfr,reception=False).order_by('-id')


    # VALIDATION DE LA DEMANDE
    hide_form = True
    form = DocIdForm2(request.POST, request.FILES)
    if request.method == 'POST':
        if 'valdem' in request.POST:
            form = DocIdForm2(request.POST, request.FILES)
            if form.is_valid():
                cd = form.cleaned_data
                dem = cd.get('dem')
                doc = cd.get('document')

                demande = DemandeActes.objects.get(id=dem)
                ReponseDemandeActes.objects.create(
                    demande=demande,
                    document=doc
                )
                demande.reception = True
                demande.save()
                messages.success(request, 'Demande traitée')
                return redirect('/scolarite/demande_list/')
            else:
                messages.error(request, 'Vérifiez les champs svp')
                return redirect('/scolarite/demande_list/')

    form2 = GenererForm()
    typedem = None
    an = None
    nce = ''
    if request.method == 'POST':
        if 'generer' in request.POST:
            form2 = GenererForm(request.POST, request.FILES)
            if form2.is_valid():
                cd = form2.cleaned_data
                typedem = TypeDemandeActes.objects.get(id=cd.get('typedem'))
                nce = cd.get('nce')
                an = Annee.objects.get(id=cd.get('annee'))
                hide_form = False

    # ON RECUPERE L'ETUDIANT
    if ags:
        etudiant = Etudiant.objects.filter(nce=nce).last()
    else:
        etudiant = Etudiant.objects.filter(nce=nce,ufr__in=ensUfr).last()

    DemandeFilter = DemandeActes.objects.filter(annee=an,etudiant=etudiant,type_demande=typedem).order_by('created')

    etnv =  get_semestre_niveau_by_annee(etudiant,an)


    context = {
        'demandes': demandes,
        'hide_form': hide_form,
        'form': form,
        'form2': form2,
        'user': user,
        'etudiant': etudiant,
        'annees': annees,
        'typeDemandes': typeDemandes,
        'typedem': typedem,
        'an': an,
        'DemandeFilter': DemandeFilter,
        'sem': etnv,
    }
    return render(request, 'scolarite/demainde_list.html', context)
