from BasicData.models import Enseignant, Note,Etudiant,Evaluation,TypeEvaluation,Ecue,Session,Annee,Deliberation
import numpy as np
import time
from datetime import datetime


#TODO: Calcul de Moyenne
def get_etudian_moyenne(etudiant, ecue, session):
    note_list = []
    moyenne=0
    # On recupere les evaluations de l'ecue par session
    evaluations = Evaluation.objects.filter(ecue=ecue, session=session)
    for evaluation in evaluations:
        # On recupere les notes de chaque evalutions par etudiant
        notes = Note.objects.filter(etudiant__nce=etudiant, evaluation_id=evaluation.id)
        for note in notes:
            # Recupere la note de : Examen
            if note.evaluation.typeEvaluation.id == 1:
                total = note.note * 0.6
                note_list.append(total)
            else:
                total = note.note * 0.4
                note_list.append(total)

        moyenne = sum(note_list)
    return moyenne


#TODO: GET NOTE
def get_evalution_note(etudiant,annee,ecue,enseignant):
    # On Recupere toute les evaluations de l'enseignant
    eval_note =''
    note_etudiant = []
    EvalEnsg = Evaluation.objects.filter(ecue=ecue,annee=annee)
    # pour chaque evaluation on recupere la de l'etudiant
    for EnsEval in EvalEnsg:
        try:
            notes = Note.objects.get(etudiant=etudiant, evaluation=EnsEval,annee=annee,ecue=ecue)
            eval_note = notes.note
        except Note.DoesNotExist:
            notes = None
            eval_note = 0
        note_etudiant.append(eval_note)
    return note_etudiant


#TODO: GET MOYENNE ECUE
def get_moyenne_ecue(etudiant,annee,ecue,enseignant,test):
    # On recupere les evaluations de l'ecue
    evaluations = Evaluation.objects.filter(ecue=ecue.id, annee=annee)
    # 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
    session = None
    resultat = 0
    for evaluation in evaluations:
        try:
            #pour chaque etudiant on recuper les note
            notes_cc2 = Note.objects.get(etudiant=etudiant, evaluation=evaluation, annee=annee,ecue=ecue)
            if evaluation.typeEvaluation.libelle == 'Contrôle Continu':
                tottal_cc += notes_cc2.note
                nombre_cc += 1
            else:
                tottal_ue += notes_cc2.note
                nombre_ue += 1
                session = evaluation.session
        except Note.DoesNotExist:
            notes_cc2 = None
    # CALCUL DE MOYENNE CC
    moyenne_cc = 0
    if nombre_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

    if test =='mecue':
        resultat = myenne_generale
    elif test == 'sess':
        resultat = session

    return resultat


#TODO: GET ECUE DELIBERATION
def get_seuil_deliberation_ecue(annee,ecue,session):
    seuil = 0
    try:
        deliberation = Deliberation.objects.filter(ecue=ecue, annee=annee, session=Session.objects.get(id=1)).last()  #
    except Deliberation.DoesNotExist:
        deliberation = 0
        
    if deliberation:
        seuil = deliberation.note
    else:
        seuil =0
    resultat = seuil
    return resultat


#TODO: GET LIST DISTINCT VALUES
def cleaned_list(list1):
    x = np.array(list1)
    unik = np.unique(x)
    return unik

#TODO: 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

#TODO: TROUVER LA DUREE ENTRE DEUX TEMPS
def get_duree(horaire):
    horair = horaire.split('-')
    dheur = horair[0].split(':')
    fheur = horair[1].split(':')

    duree = []
    if dheur[1] > fheur[1]:
        fh = int(fheur[0])
        fm = int(fheur[1])
        fheur[0] = fh - 1
        fheur[1] = fm + 60

    # On clacul la durée
    duree.append(int(fheur[0])-int(dheur[0]))
    duree.append(int(fheur[1])-int(dheur[1]))

    mp = map(str,duree)
    nduree = ':'.join(mp)
    return nduree

#TODO: SPLIT HORAIRE
def get_horaire_split(horaire,periode):
    horair = []
    dheur = []
    fheur = []
    resultat = ''
    if '-' in horaire :
        horair = horaire.split('-')
        dheur =[]
        fheur =[]
        if ':' in horair[0]:
            dheur = horair[0].split(':')
        else:
            dheur =[0]
        if ':' in horair[1]:
            fheur = horair[1].split(':')
        else:
            fheur =[0]

        #print(dheur)

        debut = dheur[0]
        fin = fheur[0]
        if periode =='debut':
            resultat =int(debut)
        elif periode =='fin':
            resultat = int(fin)

    return resultat

#TODO: CHECK GROUP __ EMPLOIS DU TEMPS ___
def group_check(request):
    group_checked = None
    for g in request.user.groups.all():
        if g.name == 'emplois du temps':
            group_checked = 1
    return group_checked


def calcTime(enter,exit):
    format="%H:%M:%S"
    #Parsing the time to str and taking only the hour,minute,second
    #(without miliseconds)
    enterStr = str(enter).split(".")[0]
    exitStr = str(exit).split(".")[0]
    #Creating enter and exit time objects from str in the format (H:M:S)
    enterTime = datetime.strptime(enterStr, format)
    exitTime = datetime.strptime(exitStr, format)
    return exitTime - enterTime


def get_next_or_prev(instance, direction):

    # ON RECUPERE L'ID DE L'INSTANCE
    instance_id = instance.id
    qs =instance
    if direction == 'prev':
        qs = instance.__class__.objects.filter(id__lt=instance_id).first()
    elif direction == 'next':
        qs = instance.__class__.objects.filter(id__gt=instance_id).first()
    elif direction == 'now':
        qs = instance

    return qs