from django.shortcuts import render,redirect

from BasicData.custom_fonctions import get_next_or_prev
from BasicData.models import *
from django.http import HttpResponse
import pandas as pd
from django.contrib.auth.decorators import login_required
import csv

# Create your views here.
from BasicData.templatetags.custom_tag import get_credit_valide_semestre_ufr, get_decision_annuelle_etudiant, \
    get_etudiant_moyenne_ue_session_1, get_etudiant_session_2_moy_ue, get_etudiant_moyenne_ue3
from BasicData.templatetags.custom_tag_obj import get_etudiant_list, get_parcours, get_credit_semestre_ufr, \
    get_ecue_etudiant, get_note_delib_ue, generer_password


@login_required(login_url='BasicData:login')
def groupe_etudiant_export(request,id):
    # ON RECUPERE LE GROUPE
    groupe = GroupTravail.objects.get(id=id)
    # ENSEIGNANT DU GROUPE
    students = GroupEtudiant.objects.filter(groupe=groupe)
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename='+str(groupe.annee)+'_'+str(groupe.niveau.libelle)+'_'+str( groupe.ufr.code)+'_'+str(groupe.libelle)+'.csv'
    writer = csv.writer(response,delimiter=';')
    writer.writerow(['ID', 'NOM', 'PRENOMS', 'SEXE'])
    studs = students.values_list('etudiant__nce','etudiant__nom','etudiant__prenoms','etudiant__sexe')
    for std in studs:
        writer.writerow(std)
    return response



@login_required(login_url='BasicData:login')
def dr_ufr_etudiant_ecue_export(request,id,an):
    # ROLE
    #user = enseign = Enseignant.objects.get(email=request.user.email)
    annee = Annee.objects.get(id=an)

    # On recupere les infos UE de l'Ecue
    ue = Ecue.objects.get(id=id).ue
    ecue = Ecue.objects.get(id=id)

    # PARAMETRE POUR LE FILTRE
    args = [annee.id, ue.ufr.id, ue.niveau.id, ecue.id]

    # ON RECUPERE L'ANNEE PRECEDENTE
    prevAnnee = get_next_or_prev(annee, 'prev')
    nextAnnee = get_next_or_prev(annee, 'next')

    # PAR DEFAUT
    etudiantUes = get_ecue_etudiant(args)

    if prevAnnee:
        deliberation_note = DeliberationUe.objects.filter(annee=prevAnnee, ue=ue).last()
        del_note = 10
        if deliberation_note:
            del_note = deliberation_note.note

        etudiant_list = [etd for etd in get_etudiant_list([prevAnnee.id, ue.niveau.id, ue.ufr.id]) if
                         get_etudiant_moyenne_ue3([etd,prevAnnee],ue) < del_note
                         and NiveauEtudiant.objects.filter(annee=nextAnnee,etudiant=etd)
                         ]

        set_list = [et for et in etudiant_list if etudiantUes.count(et) == 0]

        for stud in set_list:
            etudiantUes.append(stud)

    # ON ORDONNE LA LISTE
    etudiantUes.sort(key=lambda x: x.nom)
    students = Etudiant.objects.filter(id__in=[etds.id for etds in etudiantUes])

    ############################
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename=LISTE_'+str(ecue.code)+'_'+str(annee.libelle)+'.csv'
    writer = csv.writer(response,delimiter=';')
    writer.writerow(['NCE', 'NOM', 'PRENOMS','NOTE'])
    #studs = etudiantUes.values_list('etudiant__nce','etudiant__nom','etudiant__prenoms','etudiant__sexe')
    studs = students.values_list('nce','nom','prenoms')
    for std in studs:
        writer.writerow(std)
    return response


@login_required(login_url='BasicData:login')
def pv_annuel_export(request, annee, niveau, ufr):
    # On recupere l'UFR
    UFR = Ufr.objects.get(id=ufr)
    ############################################

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

    # ON RECUPERE LES ETUDIANTS
    qs = [et.id for et in get_etudiant_list([get_annee.id, get_niveau.id, UFR.id])]
    etudiants = Etudiant.objects.filter(id__in=qs)

    IDP = [et.nce for et in etudiants]                  # 1- IDENTIFIANT PERMANENT
    ancien_nce = [et.ancien_nce for et in etudiants]    # 2- NUMERO CARTE ETUDIANT
    mat_men = ['---' for et in etudiants]                  # 3- MATRICULE MEN
    numero_bac = [et.numero_bac for et in etudiants]    # 4- NUMERO TABLE BAC
    nom = [et.nom for et in etudiants]                  # 5- NOM

    prenom = [et.prenoms for et in etudiants]           # 6- PRENOMS
    datenaiss = [et.datenaiss for et in etudiants]      # 7- DATE DE NAISSANCE
    lieunaiss = [et.lieunaiss for et in etudiants]      # 8- LIEU DE NAISSANCE
    sexe = [et.sexe for et in etudiants]                # 9- SEXE
    nationalite = [et.nationalite for et in etudiants]  # 10- NATIONALITE

    annee_pv = [get_annee for et in etudiants]          # 11- ANNEE PV
    annee_insc = ['---' for et in etudiants]               # 12- ANNEE INSCRIPTION
    ufr = [et.ufr.code for et in etudiants]             # 13- UFR
    parcous = [get_parcours(et.ufr,get_niveau) for et in etudiants]                  # 14- PARCOURS
    niveau_etude = [get_niveau for et in etudiants]     # 15- NIVEAU ETUDDE

    parcous_derog = ['---' for et in etudiants]            # 16- PARCOURS DEROGATION
    niveau_derog = ['---' for et in etudiants]             # 17- NIVEAU ETUDE DEROGATION
    #decision_an = ['---' for et in etudiants]              # 18- DECISION FIN D'ANNEE
    statut = [et.profession for et in etudiants]        # 20- STATUT ETUDIANT
    montant = ['---' for et in etudiants]                  # 21- MONTANT

    decision_an =[] # 18- DECISION FIN D'ANNEE
    for etudiant in etudiants:
        decis_list =[]
        credit_valid =[]
        credit_sem =[]
        for sem in semestres:
            # ON RECUPERE LE DECISION PAR SEMESTRE
            decis_list.append(get_decision_annuelle_etudiant([etudiant,get_annee],sem))
            # ONRECUPERE LES CREDITS VALIDES PAR SEMESTRE
            credit_valid.append(get_credit_valide_semestre_ufr([etudiant,get_annee],sem))
            # ON RECUPERE LE TOTAL DE CREDIT PAR SELMESTRE
            credit_sem.append(get_credit_semestre_ufr([etudiant.ufr.id,get_annee.id],sem.id))

        # TOTAL CREDITS VALIDES ANNUEL
        tot_cred_val = sum(credit_valid)
        # TOTAL CREDITS ANNUEL
        total_credit = sum(credit_sem)
        # ON CALCUL LE TAUX DE VALIDATION ANNUEL
        taux_an=0
        if total_credit !=0:
            taux_an = (tot_cred_val/total_credit)*100

        decision =''
        if len(decis_list)>1:
            decision_S1 = decis_list[0]
            decision_S2 = decis_list[1]

            if (decision_S1 == 'ADMIS(E)' and decision_S2 == 'ADMIS(E)') or taux_an == 100:
                decision = 'ADMIS(E)'
            elif (decision_S1 == 'ADMIS(E)' and decision_S2 == 'AUTORISE(E)') or 80 <= taux_an < 100:
                decision = 'AUTORISE(E)'
            elif (decision_S1 == 'AUTORISE(E)' and decision_S2 == 'ADMIS(E)') or 80 <= taux_an < 100:
                decision = 'AUTORISE(E)'
            elif (decision_S1 == 'AUTORISE(E)' and decision_S2 == 'AUTORISE(E)') or 80 <= taux_an < 100:
                decision = 'AUTORISE(E)'

            elif (decision_S1 == 'R' and decision_S2 == 'AUTORISE(E)') and 80 <= taux_an < 100:
                decision = 'AUTORISE(E)'
            elif (decision_S1 == 'AUTORISE(E)' and decision_S2 == 'R') and 80 <= taux_an < 100:
                decision = 'AUTORISE(E)'
            elif (decision_S1 == 'R' and decision_S2 == 'ADMIS(E)') and 80 <= taux_an < 100:
                decision = 'AUTORISE(E)'
            elif (decision_S1 == 'ADMIS(E)' and decision_S2 == 'R') and 80 <= taux_an < 100:
                decision = 'AUTORISE(E)'
            else:
                decision = 'REFUSE(E)'

        decision_an.append(decision)

    zip_data = zip(
        IDP,ancien_nce,mat_men,numero_bac,nom,
        prenom,datenaiss,lieunaiss,sexe,nationalite,
        annee_pv,annee_insc,ufr,parcous,niveau_etude,
        parcous_derog,niveau_derog,decision_an,statut,montant
    )
    #print(etudiants)

    #++++++ XLSV ++++++++++
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename='+ str(get_annee) + '_' + str(
        get_niveau.libelle) + '_' + str(UFR.code)+ '.csv'
    writer = csv.writer(response,delimiter=';')
    writer.writerow([
        'IDENTIFIANT PERMANENT', 'NUMERO CARTE ETUDIANT', 'MATRICULE MEN', 'NUMERO TABLE BAC','NOM',
        'PRENOMS','DATE DE NAISSANCE','LIEU DE NAISSANCE','SEXE','NATIONALITE',
        'ANNEE PV','ANNEE INSCRIPTION','UFR','PARCOURS','NIVEAU ETUDDE',
        'PARCOURS DEROGATION','NIVEAU ETUDE DEROGATION','DECISION FIN D\'ANNEE','STATUT ETUDIANT','MONTANT'
    ])
    studs = zip_data
    for std in studs:
        writer.writerow(std)
    return response


@login_required(login_url='BasicData:login')
def etudiant_inscrit_export(request):
    # ON RECUPERE LE GROUPE
    #groupe = GroupTravail.objects.get(id=id)
    # ENSEIGNANT DU GROUPE
    students = [ et.etudiant for et in NiveauEtudiant.objects.filter(annee=Annee.objects.last()) if '@usp.edu.ci' not in et.etudiant.email]
    IDP = []
    NOM = []
    PRNS = []
    MAIL = []
    PSW = []
    QT = []
    for etudiant in students:
        IDP.append(etudiant.nce)
        NOM.append(etudiant.nom)
        PRNS.append(etudiant.prenoms)
        pr = str(etudiant.prenoms).split(' ')[0].lower().replace("'","")
        MAIL.append(str(etudiant.nom).lower().replace("'","")+'.'+str(pr)+'22'+str(etudiant.ufr.libelle)[0])
        PSW.append(generer_password(8))
        QT.append(10)

    zip_data = zip(IDP,NOM,PRNS,MAIL,PSW,QT)

    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename=EMAIL_INSTITUTIONNEL.csv'
    writer = csv.writer(response,delimiter=';')
    writer.writerow(['ID', 'Nom', 'Prenoms', 'Email','Password','Quota'])
    studs = zip_data
    for std in studs:
        writer.writerow(std)
    return response