from functools import reduce
from urllib import request

from django import template
import datetime
import operator

from BasicData.custom_fonctions import calcTime, get_next_or_prev
from BasicData.models import Note, SyllabusEcue, Enseignant, Reclamations, EnseignantUfr, Etudiant, Evaluation, Ue, \
    Ecue, Annee, Deliberation, DeliberationUe, EmploiDuTemps2, SeanceCours, NiveauEtudiant, Semestre, Presence

# déclarations de la librairie
from django.db.models import Sum

from BasicData.templatetags.custom_tag_obj import get_ecue_by_ufr_and_semestre, get_ue_by_ufr_and_semestre, \
    get_ue_by_ufr_and_semestre_set, get_note_delib_ue, get_ue_by_ufr_set, get_credit_ufr, get_niveau_etudiant, \
    get_credit_semestre_ufr, get_compens_note, get_ecue_etudiant, get_etudiant_list

register = template.Library()
# -----------------

# TODO: Today date
y = datetime.datetime.now().year
m = datetime.datetime.now().month
d = datetime.datetime.now().day
date = str(d) + "-" + str(m) + "-" + str(y)

@register.filter(name='get_today')
def get_today(sep):
    y = datetime.datetime.now().year
    m = datetime.datetime.now().month
    d = datetime.datetime.now().day
    if len(str(d))==1:
        d = '0'+str(d)
    if len(str(m))==1:
        m = '0'+str(m)
    date = str(d) + str(sep) + str(m) + str(sep) + str(y)
    return date

# Trouver la difference entre une date et la date actuel(format de date: 0000-00-00)
@register.filter(name='get_age')
def get_age(value, key):
    year_now = datetime.datetime.today().year
    year_str = str(value).split(key)[0]
    year_int = int(year_str)
    age = year_now - year_int
    return age


@register.filter(name='get_evalution_note')
def get_evalution_note(value, key):
    # On recupere la note en fonction de l'etudiant et de l'evaluation
    eval_note = 0
    try:
        #notes = Note.objects.filter(etudiant__id=1117).last()
        notes = Note.objects.get(etudiant=value, evaluation=key,annee=Annee.objects.last())
    except Note.DoesNotExist:
        notes = None

    if notes:
        eval_note = notes.note
    print('['+str(value)+']'+str(Etudiant.objects.get(id=value))+' === '+str(notes))
    return round(eval_note,2)


#TODO: GET EVALUATION
@register.filter(name='get_evalution_note2')
def get_evalution_note2(value, args):
    ##### args = [evaluation,annee] #####
    evaluation = args[0]
    annee = args[1]
    session = args[2]

    # On recupere la note en fonction de l'etudiant et de l'evaluation
    eval_note = 0

    notes = Note.objects.filter(etudiant__id=value, evaluation__id=evaluation.id, annee__id=annee.id,evaluation__session__id=session.id).last()
    if notes:
        eval_note = notes.note

    return round(eval_note,2)
    #return eval_note


@register.filter(name='get_evalution_note3')
def get_evalution_note3(evaluation , args):
    ##### args = [evaluation,annee] #####
    etudiant = args[0]
    annee = args[1]
    # On recupere la note en fonction de l'etudiant et de l'evaluation
    eval_note = 0
    notes = Note.objects.filter(etudiant=etudiant, evaluation=evaluation, annee=annee).last()
    if notes:
        eval_note = notes.note
    return round(eval_note,2)

@register.filter(name='get_moyenne_cc')
def get_moyenne_cc(value, key):

    # On recupere l'Ecue et son UE
    #ue = Ue.objects.get(id=key)
    ecue = Ecue.objects.get(id=key)
    evaluations = Evaluation.objects.filter(ecue=ecue.id, annee=Annee.objects.last())
    #print(len(evaluations))
    # On recupere tout les notes de cc en fonction de (etudiant,evaluation,annee)
    # Pour chaque evaluations on recupere les de l'etudiant
    tottal_cc = 0
    nombre_cc =0
    resultat = 0
    if evaluations:
        for evaluation in evaluations:
            if evaluation.typeEvaluation.id == 2: # Controle Continu
                notes_cc = Note.objects.filter(etudiant=value, evaluation=evaluation, annee=evaluation.annee,ecue=ecue)
                for note in notes_cc:
                    tottal_cc += note.note
                    nombre_cc += 1
                    #print(note.note)

        # CALCUL DE MOYENNE CC
        moyenne_cc =0
        if nombre_cc !=0:
            moyenne_cc= tottal_cc/nombre_cc
        else:
            moyenne_cc = 0

        resultat = moyenne_cc
    return round(resultat,2)


@register.filter(name='get_moyenne_ue')
def get_moyenne_ue(value, key):
    # On recupere l'Ecue et son UE
    ecue = Ecue.objects.get(id=key)
    evaluations = Evaluation.objects.filter(ecue=ecue.id, annee=Annee.objects.last())

    # On recupere tout les notes de cc en fonction de (etudiant,evaluation,annee)
    # Pour chaque evaluations on recupere les de l'etudiant
    tottal_cc = 0
    nombre_cc = 0
    tottal_ue = 0
    nombre_ue = 0
    for evaluation in evaluations:
        if evaluation.typeEvaluation.id == 2: # Controle Continu
            notes_cc = Note.objects.filter(etudiant=value, evaluation=evaluation, annee=evaluation.annee,ecue=ecue)
            for note in notes_cc:
                tottal_cc += note.note
                nombre_cc += 1
        else:
            notes_cc = Note.objects.filter(etudiant=value, evaluation=evaluation, annee=evaluation.annee,ecue=ecue)
            for note in notes_cc:
                tottal_ue += note.note
                nombre_ue += 1

    # CALCUL DE MOYENNE CC
    moyenne_cc = 0
    if tottal_cc != 0:
        moyenne_cc = tottal_cc / nombre_cc
    else:
        moyenne_cc = 0

    # CALCUL DE MOYENNE UE

    if nombre_ue != 0:
        moyenne_ue = tottal_ue/ nombre_ue
        # MOYENNE GENERALE
        myenne_generale = (moyenne_cc * 0.4) + (moyenne_ue * 0.6)
    else:
        moyenne_ue = 0
        myenne_generale =0


    resultat = myenne_generale
    return round(resultat,2)


#TODO: CLONE GET_MOYENNE_UE ********************
@register.filter(name='get_moyenne_ue2')
def get_moyenne_ue2(etudiant, args):
    ecue = args[0]
    annee = args[1]
    #session = args[2]
    # On recupere l'Ecue et son UE
    evaluations = Evaluation.objects.filter(ecue=ecue, annee=annee)
    total_note = sum([Note.objects.filter(etudiant=etudiant, evaluation=evaluation, annee=evaluation.annee, ecue=ecue).last().note * evaluation.typeEvaluation.pourcentage for evaluation in evaluations if evaluation and Note.objects.filter(etudiant=etudiant, evaluation=evaluation, annee=evaluation.annee, ecue=ecue).last()])
    coeff = sum([evaluation.typeEvaluation.pourcentage for evaluation in evaluations if evaluation])

    resultat = 0
    if coeff >0:
        resultat = total_note / coeff
    return round(resultat,2)


#TODO : DELIBERATION
@register.filter(name='deliberation')
def deliberation(value, key):
    # On recupere l'Ecue et son UE
    ecue = Ecue.objects.get(id=key)
    evaluations = Evaluation.objects.filter(ecue=ecue.id, annee=Annee.objects.last())
    resultat = 0
    session = None
    if evaluations:
        # On recupere tout les notes de cc en fonction de (etudiant,evaluation,annee)
        # Pour chaque evaluations on recupere les de l'etudiant
        tottal_cc = 0
        nombre_cc = 0
        tottal_ue = 0
        nombre_ue = 0
        resultat = ''
        for evaluation in evaluations:
            if evaluation.typeEvaluation.id == 2: # Controle Continu
                notes_cc = Note.objects.filter(etudiant=value, evaluation=evaluation, annee=evaluation.annee,ecue=ecue)
                for note in notes_cc:
                    tottal_cc += note.note
                    nombre_cc += 1
            else:
                notes_cc = Note.objects.filter(etudiant=value, evaluation=evaluation, annee=evaluation.annee,ecue=ecue)
                for note in notes_cc:
                    tottal_ue += note.note
                    nombre_ue += 1
                    session = evaluation.session

        # CALCUL DE MOYENNE CC
        moyenne_cc = 0
        if tottal_cc != 0:
            moyenne_cc = tottal_cc / nombre_cc
        else:
            moyenne_cc = 0

        # CALCUL DE MOYENNE UE
        moyenne_ue = 0
        if tottal_ue != 0:
            moyenne_ue = tottal_ue / nombre_ue
        else:
            moyenne_ue = 0

        #MOYENNE GENERALE
        moyenne_generale = (moyenne_cc*0.4) + (moyenne_ue*0.6)

        #ON RECUPERE LE SEUIL DE DELIBERATION DE L'ECUE
        Ecu = None
        for evaluat in evaluations:
            Ecu = evaluat.ecue
        annee = Annee.objects.last()

        if Ecu and annee and session:
            try:
                deliberation = Deliberation.objects.filter(ecue=Ecu,annee=annee,session=session).last()
                if deliberation:
                    seuil = deliberation.note
                else:
                    seuil = 0
                # ON FAIT LA DELIBERATION
                resultat = ''
                if moyenne_generale >= seuil:
                    resultat = 'Validé'
                else:
                    resultat = 'Ajourné'
            except Deliberation.DoesNotExist:
                resultat = ''

    return resultat


#TODO : CLONE DELIBERATION ********************
@register.filter(name='deliberation2')
def deliberation2(value, args):
    ecue = Ecue.objects.get(id=args[0])
    annee = args[1]
    session = args[2]

    # On recupere l'Ecue et son UE
    evaluations = Evaluation.objects.filter(ecue__id=ecue.id, annee__id=annee.id,session__id=session.id)
    resultat = ''
    session = None
    if evaluations:
        # On recupere tout les notes de cc en fonction de (etudiant,evaluation,annee)
        # Pour chaque evaluations on recupere les de l'etudiant
        tottal_cc = 0
        nombre_cc = 0
        tottal_ue = 0
        nombre_ue = 0
        resultat = ''
        for evaluation in evaluations:
            if evaluation.typeEvaluation.id == 2: # Controle Continu
                notes_cc = Note.objects.filter(etudiant=value, evaluation=evaluation, annee=evaluation.annee,ecue=ecue)
                for note in notes_cc:
                    tottal_cc += note.note
                    nombre_cc += 1
            else:
                notes_cc = Note.objects.filter(etudiant=value, evaluation=evaluation, annee=evaluation.annee,ecue=ecue)
                for note in notes_cc:
                    tottal_ue += note.note
                    nombre_ue += 1
                    session = evaluation.session

        # CALCUL DE MOYENNE CC
        moyenne_cc = 0
        if tottal_cc != 0:
            moyenne_cc = tottal_cc / nombre_cc
        else:
            moyenne_cc = 0

        # CALCUL DE MOYENNE UE
        moyenne_ue = 0
        if tottal_ue != 0:
            moyenne_ue = tottal_ue / nombre_ue
        else:
            moyenne_ue = 0

        #MOYENNE GENERALE
        moyenne_generale = (moyenne_cc*0.4) + (moyenne_ue*0.6)

        #ON RECUPERE LE SEUIL DE DELIBERATION DE L'ECUE
        Ecu = None
        for evaluat in evaluations:
            Ecu = evaluat.ecue
        #annee = Annee.objects.last()

        if Ecu and annee and session:
            try:
                deliberation = Deliberation.objects.filter(ecue=Ecu,annee=annee,session=session).last()
                if deliberation:
                    seuil = deliberation.note
                else:
                    seuil = 0
                # ON FAIT LA DELIBERATION
                resultat = ''
                if moyenne_generale >= seuil:
                    resultat = 'Validé'
                else:
                    resultat = 'Ajourné'
            except Deliberation.DoesNotExist:
                resultat = ''

    return resultat


#TODO : DELIBERATION SESSION 2 ********************
@register.filter(name='deliberation_session')
def deliberation_session(etudiant, args):
    ecue = Ecue.objects.get(id=args[0])
    annee = args[1]
    session = args[2]

    # ON RECUPERE LA NOTE DE LA SESSION
    note_session_obj = Note.objects.filter(etudiant=etudiant,ecue=ecue,annee=annee,evaluation__session=session).last()
    note_sess =0
    if note_session_obj:
        note_sess = note_session_obj.note

    # ON RECUPERE LA NOTE DE DELIBERATION DE LA SESSION
    delib_sess_obj = Deliberation.objects.filter(ecue=ecue,annee=annee,session=session).last()
    note_delib = 0
    if delib_sess_obj:
        note_delib = delib_sess_obj.note

    # ON DEFINIT LA DELIBERATION
    resultat =''
    if note_sess >= note_delib:
        resultat = 'Validé'
    else:
        resultat = 'Ajourné'

    return resultat


#TODO: GET ETUDIANT MOYENNE ECUE
@register.filter(name='get_etudiant_moyenne_ecue')
def get_etudiant_moyenne_ecue(etudiant, ecue):
    # On recupere toutes les notes de l'etudiant dans l'ecue
    notes = Note.objects.filter(etudiant=etudiant,ecue=ecue,annee=Annee.objects.last())
    total_cc = 0
    nombre_cc = 0
    total_ex = 0
    nombre_ex = 0
    # Trie les notes par CC et par Examen
    for note in notes:
        if note.evaluation.typeEvaluation.id==2:# Controle Continue
            total_cc += note.note
            nombre_cc +=1
        else: # 1 Examen
            total_ex += note.note
            nombre_ex += 1
    # On calcule la moyenne CC
    if nombre_cc !=0:
        moyCC = total_cc/nombre_cc
    else:
        moyCC = 0
    # On calcule moyenne de l'ecue
    moyECUE = (moyCC * 0.4)+(total_ex * 0.6)

    return round(moyECUE,2)


#TODO: GET ETUDIANT MOYENNE ECUE 2 ===========
@register.filter(name='get_etudiant_moyenne_ecue2')
def get_etudiant_moyenne_ecue2(etudiant, args):
    ecues = args[0][0]
    annee = args[1]
    # On recupere toutes les notes de l'etudiant dans l'ecue
    notes = Note.objects.filter(etudiant=etudiant,ecue=ecues,annee__id=annee)
    total_cc = 0
    nombre_cc = 0
    total_ex = 0
    nombre_ex = 0
    # Trie les notes par CC et par Examen
    for note in notes:
        if note.evaluation.typeEvaluation.id==2:# Controle Continue
            total_cc += note.note
            nombre_cc +=1
        else: # 1 Examen
            total_ex += note.note
            nombre_ex += 1
    # On calcule la moyenne CC
    if nombre_cc !=0:
        moyCC = total_cc/nombre_cc
    else:
        moyCC = 0
    # On calcule moyenne de l'ecue
    moyECUE = (moyCC * 0.4)+(total_ex * 0.6)

    return round(moyECUE,2)


# TODO: GET ETUDIANT MOYENNE ECUE DE LA SESSION 1 ===========
@register.filter(name='get_etudiant_moyenne_ecue3')
def get_etudiant_moyenne_ecue3(args, ecue):
    etudiant = args[0]
    annee = args[1]

    moyECUE = 0
    note_S2 = check_etudiant_session_2_ecue_note(etudiant,[ecue,annee])
    delib_S2 = check_session2_delib_ue(ecue.ue.id,annee)

    if delib_S2 and note_S2:
        moyECUE = note_S2
    else:
        # On recupere toutes les notes de l'etudiant dans l'ecue
        notes = Note.objects.filter(etudiant=etudiant, ecue=ecue, annee__id=annee,evaluation__session__id=1)
        total_cc = 0
        nombre_cc = 0
        total_ex = 0
        nombre_ex = 0
        # Trie les notes par CC et par Examen
        for note in notes:
            if note.evaluation.typeEvaluation.id == 2:  # Controle Continue
                total_cc += note.note
                nombre_cc += 1
            else:  # 1 Examen
                total_ex += note.note
                nombre_ex += 1
        # On calcule la moyenne CC
        if nombre_cc != 0:
            moyCC = total_cc / nombre_cc
        else:
            moyCC = 0
        # On calcule moyenne de l'ecue
        moyECUE = (moyCC * 0.4) + (total_ex * 0.6)

    return round(moyECUE,2)

#TODO: GET ECUE CC NOTE ==== TAG:année
@register.filter(name='get_etudiant_cc_ex')
def get_etudiant_cc_ex(args, ecue):
    etudiant = args[0]
    annee = args[1]
    type = args[2]

    evEX = Evaluation.objects.filter(ecue=ecue,annee__id=annee,typeEvaluation__id=1,session__id=1).last()
    evCC = Evaluation.objects.filter(ecue=ecue,annee__id=annee,typeEvaluation__id=2,session__id=1).last()

    note = 0
    if evEX and type=='ex':
        notesEX = Note.objects.filter(etudiant=etudiant, ecue=ecue, annee__id=annee, evaluation=evEX,evaluation__session__id=1).last()
        if notesEX:
            note = notesEX.note
    elif evCC and type=='cc':
        notesCC = Note.objects.filter(etudiant=etudiant, ecue=ecue, annee__id=annee, evaluation=evCC,evaluation__session__id=1).last()
        if notesCC:
            note = notesCC.note
    else:
        pass

    return round(note,2)

#TODO: GET ETUDIANT MOYENNE UE 2 ==== TAG:année
@register.filter(name='get_etudiant_moyenne_ue2')
def get_etudiant_moyenne_ue2(etudiant, args):
    ue = args[0] # Object
    annee = args[1] # Object

    # On recupere toute les Ecues de l'Ue
    ecues = Ecue.objects.filter(ue__id=ue.id,active=True)
    total_moyECUE =0
    nombre_ECUE =0
    # Pour ecue on recupere la moyenne de chaque Ecue grace a la fonction
    for ecue in ecues:
        # total ECUE pondéré (moy.ECUE x crédit ECUE)
        total_moyECUE += get_etudiant_moyenne_ecue2(etudiant,[[ecue],annee.id])*ecue.credit
        nombre_ECUE += ecue.credit # total crédit ECUE

    # On calcul la moyenne de l'UE
    if nombre_ECUE !=0:
        moyUE = total_moyECUE/nombre_ECUE
    else:
        moyUE = 0
    return round(moyUE,2)
    #return 30.30


#TODO: GET ETUDIANT MOYENNE UE 3 ==== TAG:année
@register.filter(name='get_etudiant_moyenne_ue3')
def get_etudiant_moyenne_ue3(args,ue):
    etudiant = args[0] # Object
    annee = args[1] # Object
    # On recupere toute les Ecues de l'Ue
    ecues = Ecue.objects.filter(ue__id=ue.id)

    tot_moyEc = sum([get_moyenne_ue2(etudiant,[ecue,annee]) for ecue in ecues])
    moyUE = 0
    if len(ecues) >0:
        moyUE = tot_moyEc / len(ecues)
    return round(moyUE,2)


#TODO: GET ETUDIANT MOYENNE UE
@register.filter(name='get_etudiant_moyenne_ue')
def get_etudiant_moyenne_ue(etudiant, ue):
    # On recupere toute les Ecues de l'Ue
    ecues = Ecue.objects.filter(ue__id=ue)
    total_moyECUE =0
    nombre_ECUE =0
    # Pour ecue on recupere la moyenne de chaque Ecue grace a la fonction
    for ecue in ecues:
        # total ECUE pondéré (moy.ECUE x crédit ECUE)
        total_moyECUE += get_etudiant_moyenne_ecue(etudiant,ecue)*ecue.credit
        nombre_ECUE += ecue.credit # total crédit ECUE

    # On calcul la moyenne de l'UE
    if nombre_ECUE !=0:
        moyUE = total_moyECUE/nombre_ECUE
    else:
        moyUE = 0
    return round(moyUE,2)

#TODO: CHECK DELIBERATION UE
@register.filter(name='check_deliberation_ue')
def check_deliberation_ue(ue,):
    annee = Annee.objects.last()
    ue = Ue.objects.get(id=ue)
    delib = DeliberationUe.objects.filter(ue=ue,annee=annee)

    resultat = ''
    if delib:
        resultat = 'Oui'
    else:
        resultat = 'Non'
    return resultat


#TODO: CHECK DELIBERATION UE/ANNEE
@register.filter(name='check_deliberation_ue_an')
def check_deliberation_ue_an(ue,an):
    ue = Ue.objects.get(id=ue)
    delib = DeliberationUe.objects.filter(ue=ue,annee=an)

    resultat = ''
    if delib:
        resultat = 'Oui'
    else:
        resultat = 'Non'
    return resultat



#TODO: CHECK DELIBERATION ECUE
@register.filter(name='check_deliberation_ecue')
def check_deliberation_ecue(ecue):
    annee = Annee.objects.last()
    ecu = Ecue.objects.get(id=ecue)
    delib = Deliberation.objects.filter(ecue=ecu,annee=annee)

    resultat = ''
    if delib:
        resultat = 'Oui'
    else:
        resultat = 'Non'

    return resultat


#TODO: CHECK DELIBERATION ECUE NEW
@register.filter(name='check_deliberation_ecue_2')
def check_deliberation_ecue_2(args,key):
    ecue = Ecue.objects.get(id=args[0])
    annee = args[1]
    session = args[2]
    delib =None
    if key =='all':
        delib = Deliberation.objects.filter(ecue=ecue,annee=annee,session=session)
    # SESSION 1
    elif key ==1:
        delib = Deliberation.objects.filter(ecue=ecue, annee=annee, session__id=1)
    # SESSION 2
    elif key ==2:
        delib = Deliberation.objects.filter(ecue=ecue, annee=annee, session__id=2)

    return delib

#TODO: CHECK IF SALLE IS ADDED
@register.filter(name='check_salle_added')
def check_salle_added(value):
    # ON RECUPERE LE PROGRAMME
    programme = EmploiDuTemps2.objects.get(id=value)

    lundi = programme.salle2_lun.all()
    mardi = programme.salle2_mar.all()
    mercredi = programme.salle2_mer.all()
    jeudi = programme.salle2_jeu.all()
    vendredi = programme.salle2_ven.all()
    samedi = programme.salle2_sam.all()


    # ON VERIFIE SI LES SALLES ONT ETE ATTRIBUEES
    resultat = ''
    if lundi or mardi or mercredi or jeudi or vendredi or samedi:
        resultat = 'existe'
    else:
        resultat = ''

    return resultat


#TODO: CHECK IF SALLE IS ADDED 2
@register.filter(name='is_salle_added')
def is_salle_added(value,day):
    # ON RECUPERE LE PROGRAMME
    programme = EmploiDuTemps2.objects.get(id=value)

    lundi = programme.salle_lun
    mardi = programme.salle_mar
    mercredi = programme.salle_mer
    jeudi = programme.salle_jeu
    vendredi = programme.salle_ven
    samedi = programme.salle_sam

    # ON VERIFIE SI LES SALLES ONT ETE ATTRIBUEES
    resultat = ''

    if lundi:
        r_lundi = 'existe'
    else:
        r_lundi = ''

    if mardi:
        r_mardi = 'existe'
    else:
        r_mardi = ''

    if mercredi:
        r_mercredi = 'existe'
    else:
        r_mercredi = ''

    if jeudi:
        r_jeudi = 'existe'
    else:
        r_jeudi = ''

    if vendredi:
        r_vendredi = 'existe'
    else:
        r_vendredi = ''

    if samedi:
        r_samedi = 'existe'
    else:
        r_samedi = ''

    if day == 'lundi':
        resultat = r_lundi
    elif day == 'mardi':
        resultat = r_mardi
    elif day == 'mercredi':
        resultat = r_mercredi
    elif day == 'jeudi':
        resultat = r_jeudi
    elif day == 'vendredi':
        resultat = r_vendredi
    elif day == 'samedi':
        resultat = r_samedi
    else:
        pass

    return resultat


#TODO: GET CREDIT UE
@register.filter(name='get_credit_ue')
def get_credit_ue(ue):
    # ON RECUPERE LES ECUES DE L'UE
    ecues =  Ecue.objects.filter(ue=ue)

    # ON COMPTABILISE LES CREDITS ECUE
    total_credit = 0
    for ecue in ecues:
        total_credit += ecue.credit

    return total_credit

#TODO: UE VALIDE CSS STYLE
@register.filter(name='is_validate')
def is_validate(moy):
    resultat =''
    if float(moy) >=10.00:
        resultat = '#92F5A6'##68A926
    else:
        resultat ='#FCF3CF'
    return resultat

#TODO: UE VALIDE CSS STYLE
@register.filter(name='is_validate_semestre')
def is_validate_semestre(decision):
    resultat =''
    if decision =='V' or decision =='A' or decision =='ADMIS(E)' or decision =='AUTORISE(E)':
        resultat = '#45B75B'#92F5A6
    else:
        resultat ='#FA7F77' #FCF3CF #68A926
    return resultat

#TODO: UE VALIDE CSS STYLE
@register.filter(name='is_validate_semestre_mpsi')
def is_validate_semestre_mpsi(moyenne):
    resultat =''
    if moyenne >=10:
        resultat = '#45B75B'#92F5A6
    else:
        resultat ='#FA7F77' #FCF3CF #68A926
    return resultat


#TODO: COMPTER LES NOUVELLES RECLAMATIONS
@register.filter(name='get_new_reclamation')
def get_new_reclamation(user,key):
    enseignant = Enseignant.objects.get(email=user)
    # ON RECUPERE LES UFRS
    ufrList = []
    for ufr in EnseignantUfr.objects.filter(enseignant=enseignant):
        ufrList.append(ufr.ufr)

    # ON RECUPERE LES RECLAMATIONS DE L'UFR
    reclamations = Reclamations.objects.filter(ufr__in=ufrList,reception=False).order_by('-id')

    #print(reclamations)
    resultat = 0
    if key =='total':
        resultat = len(reclamations)
    elif key =='liste':
        resultat = reclamations
    else:
        resultat = ''

    return resultat


#TODO: CHECK SYLLABUS
@register.filter(name='check_syllabus')
def check_syllabus(value):
    syllabus = SyllabusEcue.objects.filter(ecue__id=value)
    resultat = False
    if syllabus:
        resultat = True
    return resultat


#TODO: GET DURATION
@register.filter(name='get_total_seance_duration')
def get_total_seance_duration(user):
    seances = SeanceCours.objects.filter(enseignant=user, annee=Annee.objects.last(),admin_valid=True)
    duration=0
    duration_list =[]
    if seances:
        for seance in seances:
            duration_list.append(calcTime(seance.debut, seance.fin))
        duration = reduce(operator.add, duration_list)
        d = duration.days
        d_to_m = d * 24
        str_dur = str(duration)
        hms_data = str_dur.split(',')
        hms = ''
        if len(hms_data) > 1:
            print(hms)
            hms = hms_data[1]
        else:
            hms = hms_data[0]
        h = hms.split(':')[0]
        mt = hms.split(':')[1]
        ht = int(h) + d_to_m
        resultat = str(ht) + 'H' + str(mt)
        if resultat:
            return resultat
        else:
            return 00
    return 0


#TODO: GET DURATION FOR SEANCE IMPAYE
@register.filter(name='get_total_seance_by')
def get_total_seance_by(user,key):
    # key 0=>False, 1=>True
    seances =None
    if key == 1 or key == 0:
        seances = SeanceCours.objects.filter(enseignant=user, annee=Annee.objects.last(),paye=key,admin_valid=True)
    elif key == 'CM' or key == 'TD' or key == 'TP':
        seances = SeanceCours.objects.filter(enseignant=user, annee=Annee.objects.last(),type_cours=key,admin_valid=True)
    else:
        seances = SeanceCours.objects.filter(enseignant=user, annee=Annee.objects.last(),admin_valid=False)
    duration=0
    duration_list =[]
    if seances:
        for seance in seances:
            duration_list.append(calcTime(seance.debut,seance.fin))
        duration = reduce(operator.add, duration_list)
        d = duration.days
        d_to_m = d * 24
        str_dur = str(duration)
        hms_data = str_dur.split(',')
        hms =''
        if len(hms_data)>1:
            print(hms)
            hms = hms_data[1]
        else:
            hms =hms_data[0]
        h = hms.split(':')[0]
        mt = hms.split(':')[1]
        ht = int(h) + d_to_m
        resultat = str(ht)+'H'+str(mt)
        if resultat:
            return resultat
        else:
            return 00
    return 0


#TODO: GET DURATION BETWEEN
@register.filter(name='get_duration_between')
def get_duration_between(obj):
    hms = str(calcTime(obj.debut,obj.fin)).split(':')
    h = hms[0]
    m = hms[1]
    return str(h)+'h'+str(m)


#TODO: GET DECISION ANNUELLE ETUDIANT
@register.filter(name='get_decision_annuelle_etudiant')
def get_decision_annuelle_etudiant(args,semestre):
    etudiant = args[0]  # Object
    annee = args[1]  # Object
    # ON RECUPERE LES UES DE DU SEMESTRE DANS L'UFR
    ues = get_ue_by_ufr_and_semestre_set([etudiant.ufr.id,annee.id],semestre.id)

    total_credit =0
    cred_valid = 0
    deli_done = 0
    delib = None
    for ue in ues:
        total_credit += get_credit_ue(ue)
        if get_etudiant_moyenne_ue3([etudiant,annee],ue) >= 10:
            cred_valid += get_credit_ue(ue)
        # ON VERIFIE SI LA DELIBERATION EST FAITE POUR CETTE UE
        delib = DeliberationUe.objects.filter(annee=annee, ue=ue, session__id=1).last()
        if not delib:
            deli_done += 1


    # ON FORMULE LA DECISION
    # si tout les crédits sont validés
    # DECISION SEMESTRE 1
    if 0 < total_credit == cred_valid:
        decision = 'ADMIS(E)'
    # si crédits validés à 80% => AUTORISE
    elif total_credit > 0 and (cred_valid / total_credit) * 100 >= 80:
        decision = 'AUTORISE(E)'
    elif 0 < total_credit and (cred_valid / total_credit) * 100 < 80:
        decision = 'REFUSE(E)'
    else:
        decision = ''

    return decision


#TODO: CHECK ALL DELIBERATION DONE
@register.filter(name='check_all_ue_delib')
def check_all_ue_delib(args,semestre):
    etudiant = args[0]  # Object
    annee = args[1]  # Object

    # ON RECUPERE LES UES DE DU SEMESTRE DANS L'UFR
    #ues = get_ue_by_ufr_and_semestre(etudiant.ufr.id,semestre.id)
    ues = get_ue_by_ufr_and_semestre_set([etudiant.ufr.id,annee.id],semestre.id)

    deli_done = 0
    delib = None
    for ue in ues:
        # ON VERIFIE SI LA DELIBERATION EST FAITE POUR CETTE UE
        delib = DeliberationUe.objects.filter(annee=annee, ue=ue, session__id=1).last()
        if not delib:
            deli_done += 1
    return deli_done

#TODO: GET STATS UFR
@register.filter(name='get_stats_ufr')
def get_stats_ufr(args,key):
    ufr = args[0]  # Object
    annee = args[1]  # Object
    enseignant =0
    ue = 0
    ecue = 0
    if ufr:
        enseignant = len(EnseignantUfr.objects.filter(annee__id=annee.id, ufr__id=ufr.id).order_by('enseignant__nom'))
        ue = len(Ue.objects.filter(ufr__id=ufr.id))
        ecue = len(Ecue.objects.filter(ue__ufr__id=ufr.id))
    if key =='enseignant':
        return enseignant
    elif key == 'ue':
        return ue
    elif key =='ecue':
        return ecue
    else:
        pass


#TODO: GET TOTAL SEANCE UFR
@register.filter(name='get_total_seance_ufr')
def get_total_seance_ufr(ufr,key):
    # key 0=>False, 1=>True
    seances =None
    if ufr:
        if key == 1 or key == 0:
            seances = SeanceCours.objects.filter(ecue__ue__ufr__id=ufr,annee=Annee.objects.last(),paye=key,admin_valid=True)
        elif key == 'CM' or key == 'TD' or key == 'TP':
            seances = SeanceCours.objects.filter(ecue__ue__ufr__id=ufr,annee=Annee.objects.last(),type_cours=key,admin_valid=True)
        elif key == 'ALL':
            seances = SeanceCours.objects.filter(ecue__ue__ufr__id=ufr,annee=Annee.objects.last(),admin_valid=True)
        else:pass

    duration=0
    duration_list =[]
    if seances:
        for seance in seances:
            duration_list.append(calcTime(seance.debut,seance.fin))
        duration = reduce(operator.add, duration_list)
        d = duration.days
        d_to_m = d * 24
        str_dur = str(duration)
        hms_data = str_dur.split(',')
        hms =''
        if len(hms_data)>1:
            print(hms)
            hms = hms_data[1]
        else:
            hms =hms_data[0]
        h = hms.split(':')[0]
        mt = hms.split(':')[1]
        ht = int(h) + d_to_m
        resultat = str(ht)+'H'+str(mt)
        if resultat:
            return resultat
        else:
            return 00
    return 0


#TODO: GET TOTAL SEANCE BETWEEN
@register.filter(name='get_total_seance_between')
def get_total_seance_between(args,key):
    ens = args[0]
    debut = args[1]
    fin = args[2]
    ecue = args[3]
    ufr = args[4]
    status = args[5]
    # key 0=>False, 1=>True
    seances =None
    if key == 1 or key == 0:
        seances = SeanceCours.objects.filter(ecue__ue__ufr__id=ufr,annee=Annee.objects.last(),paye=key,admin_valid=True)
    elif key == 'CM' or key == 'TD' or key == 'TP':
        if ecue == 'tous' and ens == 'tous' and status == 'tous':
            seances = SeanceCours.objects.filter(ecue__ue__ufr=ufr, date__gte=debut,
                                                 date__lte=fin,type_cours=key,admin_valid=True).order_by('-date')

        elif ecue == 'tous' and ens != 'tous' and status == 'tous':
            seances = SeanceCours.objects.filter(ecue__ue__ufr=ufr,
                                                 enseignant=Enseignant.objects.get(id=ens), date__gte=debut,
                                                 date__lte=fin,type_cours=key,admin_valid=True).order_by('-date')

        elif ecue != 'tous' and ens == 'tous' and status == 'tous':
            seances = SeanceCours.objects.filter(ecue__ue__ufr=ufr, ecue=Ecue.objects.get(id=ecue),
                                                 date__gte=debut,
                                                 date__lte=fin,type_cours=key,admin_valid=True).order_by('-date')

        elif ecue == 'tous' and ens == 'tous' and status == 'en attente':
            seances = SeanceCours.objects.filter(ecue__ue__ufr=ufr, date__gte=debut, date__lte=fin,
                                                 admin_valid=False,type_cours=key).order_by(
                '-date')

        elif ecue == 'tous' and ens == 'tous' and status == 'validé':
            seances = SeanceCours.objects.filter(ecue__ue__ufr=ufr, date__gte=debut, date__lte=fin,
                                                 admin_valid=True,type_cours=key).order_by(
                '-date')

        elif ecue == 'tous' and ens != 'tous' and status == 'en attente':
            seances = SeanceCours.objects.filter(ecue__ue__ufr=ufr,
                                                 enseignant=Enseignant.objects.get(id=ens), date__gte=debut,
                                                 date__lte=fin,admin_valid=False,type_cours=key).order_by('-date')

        elif ecue == 'tous' and ens != 'tous' and status == 'validé':
            seances = SeanceCours.objects.filter(ecue__ue__ufr=ufr,
                                                 enseignant=Enseignant.objects.get(id=ens), date__gte=debut,
                                                 date__lte=fin, admin_valid=True,type_cours=key).order_by('-date')

        elif ecue != 'tous' and ens == 'tous' and status == 'en attente':
            seances = SeanceCours.objects.filter(ecue__ue__ufr=ufr, ecue=Ecue.objects.get(id=ecue),
                                                 date__gte=debut, date__lte=fin,
                                                 admin_valid=False,type_cours=key).order_by('-date')

        elif ecue != 'tous' and ens == 'tous' and status == 'validé':
            seances = SeanceCours.objects.filter(ecue__ue__ufr=ufr, ecue=Ecue.objects.get(id=ecue),
                                                 date__gte=debut, date__lte=fin,
                                                 admin_valid=True,type_cours=key).order_by('-date')

        elif ecue != 'tous' and ens != 'tous' and status == 'tous':
            seances = SeanceCours.objects.filter(ecue__ue__ufr=ufr, ecue=Ecue.objects.get(id=ecue),
                                                 enseignant=Enseignant.objects.get(id=ens), date__gte=debut,
                                                 date__lte=fin,type_cours=key).order_by('-date')

        elif ecue != 'tous' and ens != 'tous' and status == 'en attente':
            seances = SeanceCours.objects.filter(ecue__ue__ufr=ufr, ecue=Ecue.objects.get(id=ecue),
                                                 enseignant=Enseignant.objects.get(id=ens), date__gte=debut,
                                                 date__lte=fin, admin_valid=False,type_cours=key).order_by('-date')

        elif ecue != 'tous' and ens != 'tous' and status == 'validé':
            seances = SeanceCours.objects.filter(ecue__ue__ufr=ufr, ecue=Ecue.objects.get(id=ecue),
                                                 enseignant=Enseignant.objects.get(id=ens), date__gte=debut,
                                                 date__lte=fin, admin_valid=True,type_cours=key).order_by('-date')
        else:
            pass
    elif key == 'ALL':
        if ecue == 'tous' and ens == 'tous' and status == 'tous':
            seances = SeanceCours.objects.filter(ecue__ue__ufr=ufr, date__gte=debut,
                                                 date__lte=fin,admin_valid=True).order_by('-date')

        elif ecue == 'tous' and ens != 'tous' and status == 'tous':
            seances = SeanceCours.objects.filter(ecue__ue__ufr=ufr,
                                                 enseignant=Enseignant.objects.get(id=ens), date__gte=debut,
                                                 date__lte=fin,admin_valid=True).order_by('-date')

        elif ecue != 'tous' and ens == 'tous' and status == 'tous':
            seances = SeanceCours.objects.filter(ecue__ue__ufr=ufr, ecue=Ecue.objects.get(id=ecue),
                                                 date__gte=debut,
                                                 date__lte=fin,admin_valid=True).order_by('-date')

        elif ecue == 'tous' and ens == 'tous' and status == 'en attente':
            seances = SeanceCours.objects.filter(ecue__ue__ufr=ufr, date__gte=debut, date__lte=fin,
                                                 admin_valid=False).order_by(
                '-date')

        elif ecue == 'tous' and ens == 'tous' and status == 'validé':
            seances = SeanceCours.objects.filter(ecue__ue__ufr=ufr, date__gte=debut, date__lte=fin,
                                                 admin_valid=True).order_by(
                '-date')

        elif ecue == 'tous' and ens != 'tous' and status == 'en attente':
            seances = SeanceCours.objects.filter(ecue__ue__ufr=ufr,
                                                 enseignant=Enseignant.objects.get(id=ens), date__gte=debut,
                                                 date__lte=fin, admin_valid=False).order_by('-date')

        elif ecue == 'tous' and ens != 'tous' and status == 'validé':
            seances = SeanceCours.objects.filter(ecue__ue__ufr=ufr,
                                                 enseignant=Enseignant.objects.get(id=ens), date__gte=debut,
                                                 date__lte=fin, admin_valid=True).order_by('-date')

        elif ecue != 'tous' and ens == 'tous' and status == 'en attente':
            seances = SeanceCours.objects.filter(ecue__ue__ufr=ufr, ecue=Ecue.objects.get(id=ecue),
                                                 date__gte=debut, date__lte=fin,
                                                 admin_valid=False).order_by('-date')

        elif ecue != 'tous' and ens == 'tous' and status == 'validé':
            seances = SeanceCours.objects.filter(ecue__ue__ufr=ufr, ecue=Ecue.objects.get(id=ecue),
                                                 date__gte=debut, date__lte=fin,
                                                 admin_valid=True).order_by('-date')

        elif ecue != 'tous' and ens != 'tous' and status == 'tous':
            seances = SeanceCours.objects.filter(ecue__ue__ufr=ufr, ecue=Ecue.objects.get(id=ecue),
                                                 enseignant=Enseignant.objects.get(id=ens), date__gte=debut,
                                                 date__lte=fin).order_by('-date')

        elif ecue != 'tous' and ens != 'tous' and status == 'en attente':
            seances = SeanceCours.objects.filter(ecue__ue__ufr=ufr, ecue=Ecue.objects.get(id=ecue),
                                                 enseignant=Enseignant.objects.get(id=ens), date__gte=debut,
                                                 date__lte=fin, admin_valid=False).order_by('-date')

        elif ecue != 'tous' and ens != 'tous' and status == 'validé':
            seances = SeanceCours.objects.filter(ecue__ue__ufr=ufr, ecue=Ecue.objects.get(id=ecue),
                                                 enseignant=Enseignant.objects.get(id=ens), date__gte=debut,
                                                 date__lte=fin, admin_valid=True).order_by('-date')
        else:
            pass
    else:pass

    duration=0
    duration_list =[]
    if seances:
        for seance in seances:
            duration_list.append(calcTime(seance.debut,seance.fin))
        duration = reduce(operator.add, duration_list)
        d = duration.days
        d_to_m = d * 24
        str_dur = str(duration)
        hms_data = str_dur.split(',')
        hms =''
        if len(hms_data)>1:
            hms = hms_data[1]
        else:
            hms =hms_data[0]
        h = hms.split(':')[0]
        mt = hms.split(':')[1]
        ht = int(h) + d_to_m
        resultat = str(ht)+'H'+str(mt)
        if resultat:
            return resultat
        else:
            return 00
    return 0


#TODO: GET ETUDIANT BY ECUE (SESSION 2)
@register.filter(name='get_ecue_etudiant_session')
def get_ecue_etudiant_session(args):
    annee = args[0]
    ufr = args[1]
    niveau = args[2]
    ecue = args[3]
    ec = Ecue.objects.get(id=ecue)
    an = Annee.objects.get(id=annee)

    # ON RECUPERE LA DELIBERATION DE LA SESSION 1 DE L'ECUE
    delib = Deliberation.objects.filter(annee__id=annee, ecue__id=ecue, session__id=1).last()
    if delib:
        note = delib.note
    else:
        note = 0

    # ON RECUPERE TOUS LES ETUDIANT DE L'ECUE
    etudiants = [
       etudiant  for etudiant in get_etudiant_by_ue_list([an,ec.ue]) if get_etudiant_moyenne_ecue3([etudiant,annee],ec) < note and note >0
    ]

    return etudiants


#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


# TODO: GET ETUDIANT MOYENNE ECUE DE LA SESSION 1 ===========
@register.filter(name='get_etudiant_moyenne_ecue_session_1')
def get_etudiant_moyenne_ecue_session_1(args, ecue):
    etudiant = args[0]
    annee = args[1]

    # On recupere toutes les notes de l'etudiant dans l'ecue
    notes = Note.objects.filter(etudiant__id=etudiant, ecue__id=ecue, annee__id=annee,evaluation__session__id=1)
    total_cc = 0
    nombre_cc = 0
    total_ex = 0
    nombre_ex = 0
    # Trie les notes par CC et par Examen
    for note in notes:
        if note.evaluation.typeEvaluation.id == 2:  # Controle Continue
            total_cc += note.note
            nombre_cc += 1
        else:  # 1 Examen
            total_ex += note.note
            nombre_ex += 1
    # On calcule la moyenne CC
    if nombre_cc != 0:
        moyCC = total_cc / nombre_cc
    else:
        moyCC = 0
    # On calcule moyenne de l'ecue
    moyECUE = (moyCC * 0.4) + (total_ex * 0.6)

    return round(moyECUE,2)

# TODO: GET ETUDIANT MOYENNE ECUE DE LA SESSION 1 ===== v2 ======
@register.filter(name='get_etudiant_moyenne_ecue_session_1_v2')
def get_etudiant_moyenne_ecue_session_1_v2(etudiant,args):
    ecue = args[0]
    annee = args[1]

    # On recupere toutes les notes de l'etudiant dans l'ecue
    notes = Note.objects.filter(etudiant__id=etudiant, ecue__id=ecue, annee__id=annee,evaluation__session__id=1)
    total_cc = 0
    nombre_cc = 0
    total_ex = 0
    nombre_ex = 0
    # Trie les notes par CC et par Examen
    for note in notes:
        if note.evaluation.typeEvaluation.id == 2:  # Controle Continue
            total_cc += note.note
            nombre_cc += 1
        else:  # 1 Examen
            total_ex += note.note
            nombre_ex += 1
    # On calcule la moyenne CC
    if nombre_cc != 0:
        moyCC = total_cc / nombre_cc
    else:
        moyCC = 0
    # On calcule moyenne de l'ecue
    moyECUE = (moyCC * 0.4) + (total_ex * 0.6)

    return round(moyECUE,2)


#TODO: GET ETUDIANT MOYENNE UE SESSION 1
@register.filter(name='get_etudiant_moyenne_ue_session_1')
def get_etudiant_moyenne_ue_session_1(etudiant,args):
    ue = args[0] # Object
    annee = args[1] # Object

    # On recupere toute les Ecues de l'Ue
    ecues = Ecue.objects.filter(ue__id=ue.id)
    total_moyECUE =0
    nombre_ECUE =0
    # Pour ecue on recupere la moyenne de chaque Ecue grace a la fonction
    for ecue in ecues:
        # total ECUE pondéré (moy.ECUE x crédit ECUE)
        total_moyECUE += get_etudiant_moyenne_ecue_session_1([etudiant.id,annee.id],ecue.id)*ecue.credit
        nombre_ECUE += ecue.credit # total crédit ECUE

    # On calcul la moyenne de l'UE
    if nombre_ECUE !=0:
        moyUE = total_moyECUE/nombre_ECUE
    else:
        moyUE = 0
    return round(moyUE,2)
    #return 30.30


#TODO: GET ETUDIANT MOYENNE UE SESSION 1
@register.filter(name='get_etudiant_moyenne_ue_session_1_plus_bonus')
def get_etudiant_moyenne_ue_session_1_plus_bonus(etudiant,args):
    ue = args[0] # Object
    annee = args[1] # Object

    # On recupere toute les Ecues de l'Ue
    ecues = Ecue.objects.filter(ue__id=ue.id)
    total_moyECUE =0
    nombre_ECUE =0
    # Pour ecue on recupere la moyenne de chaque Ecue grace a la fonction
    for ecue in ecues:
        # total ECUE pondéré (moy.ECUE x crédit ECUE)
        total_moyECUE += get_etudiant_moyenne_ecue_session_1([etudiant.id,annee.id],ecue.id)*ecue.credit
        nombre_ECUE += ecue.credit # total crédit ECUE

    # On calcul la moyenne de l'UE
    if nombre_ECUE !=0:
        moyUE = total_moyECUE/nombre_ECUE
    else:
        moyUE = 0

    bonus = get_compens_note([etudiant,annee],ue)

    return round((moyUE + bonus),2)
    #return 30.30


#TODO: GET ETUDIANT NOTE SESSION 2
@register.filter(name='get_etudiant_session_2_ecue_note')
def get_etudiant_session_2_ecue_note(etudiant,args):
    ecue = args[0]  # Object
    annee = args[1]  # Object
    sess2 = Note.objects.filter(etudiant__id=etudiant.id, ecue__id=ecue.id, annee__id=annee.id,evaluation__session__id=2).last()
    if sess2:
        return sess2.note
    else:
        return 0


@register.filter(name='check_etudiant_session_2_ecue_note')
def check_etudiant_session_2_ecue_note(etudiant,args):
    ecue = args[0]  # Object
    annee = args[1]  # Object
    sess2 = Note.objects.filter(etudiant=etudiant.id, ecue__id=ecue.id, annee=annee,evaluation__session__id=2).last()
    if sess2:
        return sess2.note
    else:
        return None


@register.filter(name='get_etudiant_session_2_ecue_note_V2')
def get_etudiant_session_2_ecue_note_V2(args,ecue):
    etudiant = args[0]  # Object
    annee = args[1]  # Object
    sess2 = Note.objects.filter(etudiant__id=etudiant.id, ecue__id=ecue.id, annee__id=annee.id,evaluation__session__id=2).last()
    if sess2:
        return sess2.note
    else:
        return 0


#TODO: GET DECISON SESSION 2
@register.filter(name='get_decision_session_2_ecue_note')
def get_decision_session_2_ecue_note(moy,args):
    ecue = args[0]  # Object
    annee = args[1]  # Object
    delib = Deliberation.objects.filter(ecue__id=ecue.id, annee__id=annee.id,session__id=2).last()
    if delib and float(moy) >= delib.note:
        return 'ADMIS(E)'
    else:
        return 'AJOURNE(E)'


#TODO: GET DECISON SESSION 2
@register.filter(name='get_decision')
def get_decision(moy):
    if float(moy) >= 10:
        return 'VALIDEE'
    else:
        return 'AJOURNEE'


#TODO: GET UE DECISON SESSION 2
@register.filter(name='get_decision_session_2_ue')
def get_decision_session_2_ue(moy,args):
    ue = args[0]  # Object
    annee = args[1]  # Object
    delib = DeliberationUe.objects.filter(ue__id=ue.id, annee__id=annee.id,session__id=1).last()
    if delib and float(moy) >= delib.note:
        return 'ADMIS(E)'
    else:
        return 'AJOURNE(E)'



#TODO: GET ETUDIANT MOYENNE UE SESSION 2
@register.filter(name='get_etudiant_session_2_moy_ue')
def get_etudiant_session_2_moy_ue(etudiant,args):
    ue = args[0]  # Object
    annee = args[1]  # Object

    total_note =0
    total_credit =0
    for ecue in Ecue.objects.filter(ue__id=ue.id):
        note_S2 = get_etudiant_session_2_ecue_note(etudiant, [ecue, annee])
        if note_S2:
            total_note +=  get_etudiant_session_2_ecue_note(etudiant,[ecue,annee]) * ecue.credit
        else:
            total_note += get_etudiant_moyenne_ecue3([etudiant,annee.id], ecue) * ecue.credit
        total_credit += ecue.credit

    moy = 0
    if total_credit >0:
        moy = total_note/total_credit

    return round(moy,2)


#TODO: GET ETUDIANT MOYENNE UE SESSION 2
@register.filter(name='get_etudiant_session_2_moy_ue_plus_bonus')
def get_etudiant_session_2_moy_ue_plus_bonus(etudiant,args):
    ue = args[0]  # Object
    annee = args[1]  # Object

    total_note =0
    total_credit =0
    for ecue in Ecue.objects.filter(ue__id=ue.id):
        note_S2 = get_etudiant_session_2_ecue_note(etudiant, [ecue, annee])
        if note_S2:
            total_note +=  get_etudiant_session_2_ecue_note(etudiant,[ecue,annee]) * ecue.credit
        else:
            total_note += get_etudiant_moyenne_ecue3([etudiant,annee.id], ecue) * ecue.credit
        total_credit += ecue.credit

    moy = 0
    if total_credit >0:
        moy = total_note/total_credit

    bonus = get_compens_note([etudiant, annee], ue)

    return round((moy + bonus),2)


#TODO: CHECK SESSION 2 FOR UE
@register.filter(name='check_session2_ue')
def check_session2_ue(etudiant,args):
    ue = args[0]  # Object
    annee = args[1]  # Object
    get_ecue = 0
    for ecue in Ecue.objects.filter(ue__id=ue.id):
        note_S2 = get_etudiant_session_2_ecue_note(etudiant, [ecue, annee])
        if note_S2:
            get_ecue +=1
    return get_ecue


#TODO: CHECK SESSION 2 FOR ECUE DELIBERATION
@register.filter(name='check_session2_delib_ecue')
def check_session2_delib_ecue(ecue,annee):
    delib = Deliberation.objects.filter(ecue__id=ecue,annee__id=annee,session__id=2).last()
    return delib


@register.filter(name='check_session2_delib_ue')
def check_session2_delib_ue(ue,annee):
    delib = DeliberationUe.objects.filter(ue__id=ue,annee__id=annee,session__id=2).last()
    return delib


#TODO: CHECK SESSION 2 FOR ECUE DELIBERATION
@register.filter(name='decision_annuelle_etudiant')
def decision_annuelle_etudiant(args):
    etudiant = args
    ufr = etudiant.ufr

    # 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
    qs = NiveauEtudiant.objects.filter(annee=annee_prec,etudiant__id=etudiant.id).last()
    etniv =None
    semestres = None
    if qs:
        etniv = qs.niveau
        semestres = Semestre.objects.filter(niveau=etniv)

    # ON RECUPERE LES UE PASSE
    ues_prec = [get_ue_by_ufr_and_semestre_set([ufr.id,annee_prec.id], sem.id) for sem in semestres]

    total_credit = 0
    total_credit_valide = 0
    for ue in ues_prec:
        for u in ue:
            total_credit += get_credit_ue(u)
            moyUe = get_etudiant_moyenne_ue3([etudiant,annee_prec],u)
            note_delib_ue = get_note_delib_ue(u,annee_prec)
            if moyUe >= note_delib_ue and note_delib_ue >0:
                total_credit_valide += get_credit_ue(u)

    decision_Sems = [get_decision_annuelle_etudiant([etudiant,annee_prec],sem) for sem in semestres]
    print(decision_Sems[0])
    decS1 = ''
    decS2 = ''
    if len(decision_Sems)>1:
        decS1 = decision_Sems[0]
        decS2 = decision_Sems[1]

    # DECISION SANNUELLE
    if decS1 =='ADMIS(E)' and decS2 =='ADMIS(E)':
        decision = 'ADMIS(E)'
    elif decS1 =='ADMIS(E)' and decS2 =='AUTORISE(E)':
        decision = 'AUTORISE(E)'
    elif decS1 =='AUTORISE(E)' and decS2 =='ADMIS(E)':
        decision = 'AUTORISE(E)'
    elif decS1 =='AUTORISE(E)' and decS2 =='AUTORISE(E)':
        decision = 'AUTORISE(E)'
    elif 0 < total_credit == total_credit_valide:
       decision = 'ADMIS(E)'
    # si crédits validés à 80% => AUTORISE
    elif total_credit > 0 and (total_credit_valide / total_credit) * 100 >= 80:
        decision = 'AUTORISE(E)'
    elif 0 < total_credit and (total_credit_valide / total_credit) * 100 < 80:
        decision = 'AJOURNE(E)'
    else:
        decision = ''

    return decision


@register.filter(name='get_niveau_code')
def get_niveau_code(libelle):
    nivsplit = libelle.split(' ')
    niv = str(nivsplit[0][0].upper()) + str(nivsplit[1])
    return niv

@register.filter(name='decision_annuelle_etudiant_par_annee')
def decision_annuelle_etudiant_par_annee(args,an):
    etudiant = args
    ufr = etudiant.ufr

    # ON RECUPERE L'ANNEE PRECEDENTE
    annee_prec = Annee.objects.get(id=an.id)
    #annee_prec = Annee.objects.filter(id__lt=an).order_by('id').first()
    #print(annee_prec)

    # ON RECUPERE LE NIVEAU DE L'ETUDIANT
    qs = NiveauEtudiant.objects.filter(annee=annee_prec,etudiant__id=etudiant.id).last()
    etniv =None
    semestres = None
    if qs:
        etniv = qs.niveau
        semestres = Semestre.objects.filter(niveau=etniv)

    # ON RECUPERE LES UE PASSE
    ues_prec = [get_ue_by_ufr_and_semestre_set([ufr.id,annee_prec.id], sem.id) for sem in semestres]

    total_credit = 0
    total_credit_valide = 0
    for ue in ues_prec:
        for u in ue:
            total_credit += get_credit_ue(u)
            moyUe = get_etudiant_moyenne_ue3([etudiant,annee_prec],u)
            note_delib_ue = get_note_delib_ue(u,annee_prec)
            if moyUe >= note_delib_ue and note_delib_ue >0:
                total_credit_valide += get_credit_ue(u)

    decision_Sems = [get_decision_annuelle_etudiant([etudiant,annee_prec],sem) for sem in semestres]
    #print(decision_Sems[0])
    decS1 = ''
    decS2 = ''
    if len(decision_Sems)>1:
        decS1 = decision_Sems[0]
        decS2 = decision_Sems[1]

    # DECISION SANNUELLE
    if decS1 =='ADMIS(E)' and decS2 =='ADMIS(E)':
        decision = 'ADMIS(E)'
    elif decS1 =='ADMIS(E)' and decS2 =='AUTORISE(E)':
        decision = 'AUTORISE(E)'
    elif decS1 =='AUTORISE(E)' and decS2 =='ADMIS(E)':
        decision = 'AUTORISE(E)'
    elif decS1 =='AUTORISE(E)' and decS2 =='AUTORISE(E)':
        decision = 'AUTORISE(E)'
    elif 0 < total_credit == total_credit_valide:
       decision = 'ADMIS(E)'
    # si crédits validés à 80% => AUTORISE
    elif total_credit > 0 and (total_credit_valide / total_credit) * 100 >= 80:
        decision = 'AUTORISE(E)'
    elif 0 < total_credit and (total_credit_valide / total_credit) * 100 < 80:
        decision = 'AJOURNE(E)'
    else:
        decision = ''

    return decision


#TODO: CHECK SESSION 2 FOR ECUE DELIBERATION
@register.filter(name='decision_annuelle_etudiant_by_annee')
def decision_annuelle_etudiant_by_annee(args,annee_prec):
    etudiant = args
    ufr = etudiant.ufr

    # ON RECUPERE LE NIVEAU DE L'ETUDIANT
    qs = NiveauEtudiant.objects.filter(annee=annee_prec,etudiant__id=etudiant.id).last()
    etniv =None
    semestres = None
    ues_prec = None
    if qs:
        etniv = qs.niveau
        semestres = Semestre.objects.filter(niveau=etniv)

    # ON RECUPERE LES UE PASSE
    if semestres:
        ues_prec = [get_ue_by_ufr_and_semestre_set([ufr.id,annee_prec.id], sem.id) for sem in semestres]

    total_credit = 0
    total_credit_valide = 0
    if ues_prec:
        for ue in ues_prec:
            for u in ue:
                total_credit += get_credit_ue(u)
                moyUe = get_etudiant_moyenne_ue3([etudiant,annee_prec],u)
                note_delib_ue = get_note_delib_ue(u,annee_prec)
                if moyUe >= note_delib_ue and note_delib_ue >0:
                    total_credit_valide += get_credit_ue(u)

    decision_Sems = None
    if semestres:
        decision_Sems = [get_decision_annuelle_etudiant([etudiant,annee_prec],sem) for sem in semestres]
    decS1 = ''
    decS2 = ''
    if decision_Sems and len(decision_Sems)>1:
        decS1 = decision_Sems[0]
        decS2 = decision_Sems[1]

    # DECISION SANNUELLE
    if decS1 =='ADMIS(E)' and decS2 =='ADMIS(E)':
        decision = 'ADMIS(E)'
    elif decS1 =='ADMIS(E)' and decS2 =='AUTORISE(E)':
        decision = 'AUTORISE(E)'
    elif decS1 =='AUTORISE(E)' and decS2 =='ADMIS(E)':
        decision = 'AUTORISE(E)'
    elif decS1 =='AUTORISE(E)' and decS2 =='AUTORISE(E)':
        decision = 'AUTORISE(E)'
    elif 0 < total_credit == total_credit_valide:
       decision = 'ADMIS(E)'
    # si crédits validés à 80% => AUTORISE
    elif total_credit > 0 and (total_credit_valide / total_credit) * 100 >= 80:
        decision = 'AUTORISE(E)'
    elif 0 < total_credit and (total_credit_valide / total_credit) * 100 < 80:
        decision = 'AJOURNE(E)'
    else:
        decision = ''

    return decision


@register.filter(name='get_credit_valide_semestre_ufr')
def get_credit_valide_semestre_ufr(args,semestre):
    etudiant = args[0]
    ufr_id = etudiant.ufr.id
    annee = args[1]
    cred = sum([get_credit_ue(ue) for ue in get_ue_by_ufr_and_semestre_set([ufr_id,annee.id],semestre.id)
                if get_etudiant_moyenne_ue3([etudiant,annee],ue) >= get_note_delib_ue(ue,annee) and get_note_delib_ue(ue,annee) > 0
              ])
    return cred


@register.filter(name='get_moyenne_annuelle_etudiant')
def get_moyenne_annuelle_etudiant(args):
    etudiant = args[0]
    ufr_id = etudiant.ufr.id
    annee = args[1]

    # ON RECUPERE LE NIVEAU DE L'ETUDIANT
    niv = get_niveau_etudiant(etudiant,annee)
    moy_x_cred = 0
    moy = 0
    if niv:
        semestres = Semestre.objects.filter(niveau=niv)
        for sem in semestres:
            moy += get_moyenne_semestre_etudiant([etudiant,annee], sem)
    # ON CALCULE LA MOYENNE
    moyAn = moy / 2

    return round(moyAn,2)


@register.filter(name='get_credit_valide_annuel')
def get_credit_valide_annuel(args):
    etudiant = args[0]
    ufr_id = etudiant.ufr.id
    annee = args[1]

    niveaux = NiveauEtudiant.objects.filter(annee=annee,etudiant=etudiant).last()
    nivEt = None
    semestres = None
    if niveaux:
        nivEt = niveaux.niveau
        semestres = Semestre.objects.filter(niveau=nivEt)

    credit_val = 0
    if semestres:
        credit_val = sum([get_credit_valide_semestre_ufr([etudiant,annee],sem) for sem in semestres])

    return credit_val


@register.filter(name='get_credit_annuel_2')
def get_credit_annuel_2(args):
    etudiant = args[0]
    ufr_id = etudiant.ufr.id
    annee = args[1]

    nivEt = get_niveau_etudiant(etudiant, annee)
    semestres = Semestre.objects.filter(niveau=nivEt)

    ues =None
    if semestres:
        ues = [get_ue_by_ufr_and_semestre_set([ufr_id, annee.id], sem.id) for sem in semestres]

    set_ue =[]
    if ues:
        for ue in ues:
            for u in ue:
                set_ue.append(u)

    cred =0
    if set_ue:
        cred = sum([get_credit_ue(uest) for uest in set_ue])

    return cred


@register.filter(name='taux_credit_valide_annuel')
def taux_credit_valide_annuel(args):
    etudiant = args[0]
    ufr_id = etudiant.ufr.id
    annee = args[1]
    niv = get_niveau_etudiant(etudiant,annee)

    taux = 0
    if get_credit_ufr([ufr_id,annee.id],niv)>0:
        taux = (get_credit_valide_annuel([etudiant,annee])/get_credit_annuel_2([etudiant,annee]))*100

    return taux


@register.filter(name='get_mention')
def get_mention(moy):
    mention = ''
    if moy <= 9.99:
        mention = 'Insuffisant'
    elif moy >= 10 and moy <= 11.99:
        mention = 'Passable'
    elif moy >= 12 and moy <= 13.99:
        mention = 'Assez Bien'
    elif moy >= 14 and moy <= 15.99:
        mention = 'Bien'
    elif moy >= 16 and moy <= 17.99:
        mention = 'Très Bien'
    elif moy >= 18:
        mention = 'Excellent'
    else:
        mention = ''
    return mention


@register.filter(name='get_moyenne_semestre_etudiant')
def get_moyenne_semestre_etudiant(args,semestre):
    etudiant = args[0]
    ufr_id = etudiant.ufr.id
    annee = args[1]

    # ON RECUPERE LES UES DU SEMESTRE
    ues = get_ue_by_ufr_and_semestre_set([ufr_id, annee.id], semestre.id)

    # TOTAL MOY x CREDIT
    moy_x_cred = sum([get_credit_ue(ue) * get_etudiant_moyenne_ue3([etudiant,annee],ue) for ue in ues])
    # TOTAL CREDIT
    total_credit = get_credit_semestre_ufr([ufr_id,annee.id],semestre.id)

    moySem = 0
    if total_credit > 0:
        moySem = moy_x_cred / total_credit

    return round(moySem,2)


@register.filter(name='get_ue_ajourne')
def get_ue_ajourne(etudiant, annee):
    # ON RECUPERE L'ANNEE PRECEDENTE
    prevAnnee = get_next_or_prev(annee, 'prev')
    nextAnnee = get_next_or_prev(annee, 'next')

    # ON RECUPERE LE NIVEAU DE L'ETUDIANT
    niveau = get_niveau_etudiant(etudiant, prevAnnee)

    ue=None
    if prevAnnee:
        ue = [
                ue for ue in get_ue_by_ufr_set(etudiant.ufr.id, prevAnnee.id, niveau)
                if get_etudiant_moyenne_ue3([etudiant,prevAnnee],ue) < get_note_delib_ue(ue,prevAnnee)
                and NiveauEtudiant.objects.filter(annee=annee, etudiant=etudiant)
                #and get_niveau_etudiant(etudiant,prevAnnee) != get_niveau_etudiant(etudiant,annee)
            ]
    return ue


@register.filter(name='get_annee_validation_ue')
def get_annee_validation_ue(etudiant, ue):
    #ufr = etudiant.ufr
    annee = Annee.objects.last()
    # ON RECUPERE LES ANNEES
    annees = Annee.objects.filter(id__lte=annee.id)
    an_valid =None
    # POUR CHAQUE ANNEE ON VERIFIE SI L'UE A ETE VALIDEE
    for an in annees:
        if get_etudiant_moyenne_ue3([etudiant,an],ue) >=10 and not an_valid:
            an_valid =an
    return an_valid


# TODO: GET PDF ETUDIANT LIST
@register.filter(name='get_etudiant_by_ue_list')
def get_etudiant_by_ue_list(args):
    annee = args[0]
    ue = args[1]
    # ON RECUPERE L'ANNEE PRECEDENTE
    nowAnnee = get_next_or_prev(annee, 'now')
    prevAnnee = get_next_or_prev(annee, 'prev')
    # PAR DEFAUT
    args = [annee.id,ue.niveau.id, ue.ufr.id]
    etudiantUes = get_etudiant_list(args)
    if prevAnnee:
        deliberation_note = DeliberationUe.objects.filter(annee=prevAnnee, ue=ue).last()
        del_note = 10
        if deliberation_note:
            del_note = deliberation_note.note
        # ON RECUPERE LA LISTE DES ETUDIANTS AJOURNES DANS L'UE L'ANNEE PRECEDENTE
        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=nowAnnee, 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)
    return etudiantUes


# TODO: GET BY UE
@register.filter(name='get_etudiant_by_ue_ufr_semestre_list')
def get_etudiant_by_ue_ufr_semestre_list(args):
    annee = args[0]
    #ue = args[1]
    niveau = args[1]
    UFR = args[2]
    semestre = args[3]

    # ON RECUPERE L'ANNEE PRECEDENTE
    nowAnnee = get_next_or_prev(annee, 'now')
    prevAnnee = get_next_or_prev(annee, 'prev')

    # PAR DEFAUT
    args = [annee.id,niveau.id, UFR.id]
    etudiantUes = get_etudiant_list(args)

    # ON RECUPERE LES UE DU SEMESTRE
    ues_semestre = get_ue_by_ufr_and_semestre_set([UFR.id, annee.id], semestre.id)

    for ue in ues_semestre:
        set_list =[]
        if prevAnnee:
            deliberation_note = DeliberationUe.objects.filter(annee=prevAnnee, ue=ue).last()
            del_note = 10
            if deliberation_note:
                del_note = deliberation_note.note
            # ON RECUPERE LA LISTE DES ETUDIANTS AJOURNES DANS L'UE L'ANNEE PRECEDENTE
            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=nowAnnee, 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)
    return etudiantUes


# TODO: CHECK IF VALIDATE UE PREVIEW YEAR
@register.filter(name='check_etudiant_if_validate_ue_prev')
def check_etudiant_if_validate_ue_prev(args,ue):
    annee = args[0]
    etudiant = args[1]

    # ON RECUPERE L'ANNEE PRECEDENTE
    #nowAnnee = get_next_or_prev(annee, 'now')
    prevAnnee = get_next_or_prev(annee, 'prev')

    if prevAnnee and get_etudiant_moyenne_ue3([etudiant,prevAnnee], ue) > 10:
        return True
    else:
        return False


# TODO: GET LISTE UE NON VALIDES
@register.filter(name='get_etudiant_not_validate_ue_prev')
def get_etudiant_not_validate_ue_prev(args):
    annee = args[0]
    etudiant = args[1]

    # ON RECUPERE L'ANNEE PRECEDENTE
    #nowAnnee = get_next_or_prev(annee, 'now')
    prevAnnee = get_next_or_prev(annee, 'prev')

    # ON RECUPERE LE NIVEAU DE L'ETUDIANT
    NivEtud = get_niveau_etudiant(etudiant, prevAnnee)

    ue_ufr = None
    if NivEtud:
        ue_ufr = get_ue_by_ufr_set(etudiant.ufr.id,prevAnnee.id,NivEtud)

    ueList = []
    if prevAnnee and decision_annuelle_etudiant_by_annee(etudiant, prevAnnee)=='AUTORISE(E)':
        for ue in ue_ufr:
            if get_etudiant_moyenne_ue3([etudiant,prevAnnee], ue) < 10:
                ueList.append(ue)
    return ueList


# TODO: CHECK IF VALIDATE UE PREVIEW YEAR
@register.filter(name='get_etudiant_not_validate_edt_prev')
def get_etudiant_not_validate_edt_prev(args):
    annee = args[0]
    etudiant = args[1]

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

    # ON RECUPERE LE NIVEAU DE L'ETUDIANT
    NivEtud = get_niveau_etudiant(etudiant, prevAnnee)

    ue_ufr = None
    if NivEtud:
        ue_ufr = get_ue_by_ufr_set(etudiant.ufr.id, prevAnnee.id, NivEtud)

    ueList = []
    if prevAnnee and decision_annuelle_etudiant_by_annee(etudiant, prevAnnee) == 'AUTORISE(E)':
        for ue in ue_ufr:
            if get_etudiant_moyenne_ue3([etudiant, prevAnnee], ue) < 10:
                ueList.append(ue)
    return ueList


#TODO: GET EVALUATION
@register.filter(name='check_evalution_noted')
def check_evalution_noted(value, args):
    ##### args = [evaluation,annee] #####
    evaluation = args[0]
    annee = args[1]
    session = args[2]
    # On recupere la note en fonction de l'etudiant et de l'evaluation
    notes = Note.objects.filter(etudiant__id=value, evaluation__id=evaluation.id, annee__id=annee.id,evaluation__session__id=session.id).last()
    return notes


@register.filter(name='get_evalution_note_obj')
def get_evalution_note_obj(value, args):
    ##### args = [evaluation,annee] #####
    evaluation = args[0]
    annee = args[1]
    session = args[2]
    notes = Note.objects.filter(etudiant__id=value, evaluation__id=evaluation.id, annee__id=annee.id,evaluation__session__id=session.id).last()
    nid = None
    if notes:
        nid = notes.id
    return nid


@register.filter(name='get_evaluations_ecue')
def get_evaluations_ecue(ecue,annee):
    print(Evaluation.objects.filter(ecue=ecue, annee=annee))
    return Evaluation.objects.filter(ecue=ecue, annee=annee)


@register.simple_tag
def check_appel_ecue(date,ecue,annee,etudiant):
    if_marked = Presence.objects.filter(date=date,ecue=ecue,annee=annee,etudiant=etudiant)
    return if_marked

