from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.template.loader import get_template
from xhtml2pdf import pisa
import os
from django.conf import settings
from django.contrib.staticfiles import finders
from BasicData.models import Annee, Enseignant, Ecue, EnseignantUe, Etudiant, EtudiantUe, Evaluation, MoyenneEcue, Note, \
    ParcoursSemestreUe, Session, TypeEvaluation, Deliberation, Csv, Ue, DeliberationUe
from BasicData.custom_fonctions import get_evalution_note, get_moyenne_ecue, get_seuil_deliberation_ecue, get_mention
from BasicData.templatetags.custom_tag import get_credit_ue, get_etudiant_moyenne_ue, get_etudiant_moyenne_ue2, \
    get_etudiant_moyenne_ue3, check_session2_ue, get_etudiant_session_2_moy_ue, get_etudiant_moyenne_ecue_session_1, \
    get_etudiant_moyenne_ue_session_1, decision_annuelle_etudiant, decision_annuelle_etudiant_by_annee, \
    taux_credit_valide_annuel, get_etudiant_by_ue_ufr_semestre_list, check_etudiant_if_validate_ue_prev
from BasicData.templatetags.custom_tag_obj import get_etudiant_list, get_ue_by_ufr_and_semestre_set, get_ue_by_ufr_set, \
    get_compens_note
from .forms import *
from math import sqrt
from django.contrib import messages
import csv


def link_callback(uri, rel):
    result = finders.find(uri)
    if result:
        if not isinstance(result, (list, tuple)):
            result = [result]
        result = list(os.path.realpath(path) for path in result)
        path = result[0]
    else:
        sUrl = settings.STATIC_URL  # Typically /static/
        sRoot = settings.STATIC_ROOT
        mUrl = settings.MEDIA_URL  # Typically /media/
        mRoot = settings.MEDIA_ROOT  # Typically /home/userX/project_˓→static / media /
        if uri.startswith(mUrl):
            path = os.path.join(mRoot, uri.replace(mUrl, ""))
        elif uri.startswith(sUrl):
            path = os.path.join(sRoot, uri.replace(sUrl, ""))
        else:
            return uri

        if not os.path.isfile(path):
            raise Exception(
                'media URI must start with %s or %s' % (sUrl, mUrl)
            )


# TODO: RESULTAT ECUE
def resultat_ecue_pdf_view(request, id, an, niveau, ufr):
    annee = Annee.objects.get(id=an)
    get_niveau = Niveau.objects.get(id=niveau)
    get_ufr = Ufr.objects.get(id=ufr)

    # On recupere les infos UE de l'Ecue
    ue = Ecue.objects.get(id=id).ue
    ecue = Ecue.objects.get(id=id)
    # On recupere tout les parcourSemestreUe de la derniere année
    parcourSemestreUe = ParcoursSemestreUe.objects.filter(ue=ue, annee=annee).first()

    # on recupere les etudiants du parcourSemestreUe
    etudiantUes = [etudNiv.etudiant for etudNiv in
                   NiveauEtudiant.objects.filter(annee=annee, niveau=get_niveau, etudiant__ufr=get_ufr).order_by(
                       'etudiant__nom')]

    # On recupere l'enseignant de l'Ecue
    enseign = None

    # On recupere toute les Evaluation de L'enseignant de l'Ecue
    Evaluation_enseignant = Evaluation.objects.filter(ecue=ecue, annee=annee)

    # On recupere la note de chaque etudiant
    # for etudiant in etudiantUes:

    zip_list = []
    # recupere les notes pour chaque etudiant
    m = 'mecue'
    s = 'sess'
    for etudiant in etudiantUes:
        # on recupere les notes de l'etudiant avec la fonction get_evaluation_note
        note_etud = get_evalution_note(etudiant, annee, ecue, enseign)
        # On calcule la moyenne ecue de l'etudiant
        moy_ecue = get_moyenne_ecue(etudiant, annee, ecue, enseign, m)
        session_ev = get_moyenne_ecue(etudiant, annee, ecue, enseign, s)
        # On recupere le seuil de délibération avec la fonction
        seuil_delib = get_seuil_deliberation_ecue(annee, ecue, session_ev)
        # ON FAIT LA DELIBERATION
        if seuil_delib <= 0:
            delibereration = ''
        elif moy_ecue >= seuil_delib:
            delibereration = 'Admis'
        else:
            delibereration = 'Ajourné'

        zip_etud_note = [note_etud, etudiant.etudiant, moy_ecue, delibereration]
        zip_list.append(zip_etud_note)

    # for item in zip_list:
    # print(item[0][3][1])

    context = {
        'etudiantUes': etudiantUes,
        'ecue': ecue,
        'EvalEns': Evaluation_enseignant,
        'zip_list': zip_list,
        'get_annee': annee,
        'get_niveau': get_niveau,
        'get_ufr': get_ufr,
    }

    template_path = 'bulletin/resultat_pdf.html'

    # Create a Django response object, and specify content_type as pdf
    response = HttpResponse(content_type='application/pdf')
    # if download
    # response['Content-Disposition'] = 'attachment; filename="report.pdf"'
    # if display
    response['Content-Disposition'] = 'filename="resultat_ecue.pdf"'
    # find the template and render it.
    template = get_template(template_path)
    html = template.render(context)

    # create a pdf
    pisa_status = pisa.CreatePDF(
        html, dest=response, link_callback=link_callback)
    # if error then show some funy view
    if pisa_status.err:
        return HttpResponse('We had some errors <pre>' + html + '</pre>')
    return response


# TODO:RESUTAT UE
def resultat_ue_pdf_view(request, id, an):
    annee = Annee.objects.get(id=an)
    # On recupere l'enseignant
    enseignant = Enseignant.objects.get(email=request.user.email)
    # O recupere les UE de l'Enseignant
    EnseignantUes = EnseignantUe.objects.filter(enseignant=enseignant, annee=annee)
    UEs = []
    EtudMoyList = []
    EtudianList = []
    DelibList = []
    MentionList = []
    annee_univ = annee
    for enst in EnseignantUes:
        UEs = Ue.objects.get(id=enst.ecue.ue.id)

    # On recupere tout les etudiant de cette UE
    etudiantUEs = EtudiantUe.objects.filter(parcoursSemestreUe__ue=UEs)
    # On recupere la deliberation
    try:
        seuil_delib1 = DeliberationUe.objects.get(ue=UEs, annee=annee_univ, session__libelle='Session 1')
    except DeliberationUe.DoesNotExist:
        seuil_delib1 = None

    if seuil_delib1:
        seuil_delib = seuil_delib1.note
    else:
        seuil_delib = 0

    # Pour chaque etudiant on calcule la moyenne UE
    for etudiantUE in etudiantUEs:
        # print(etudiantUE.etudiant.nom)
        # Pour chaque etudiant on calcule la moyenne ECUE
        total_moyEcue = 0
        nombre_moyEcue = 0
        for etudEcue in EnseignantUes:
            total_moyEcue += get_moyenne_ecue(etudiantUE.etudiant, annee_univ, etudEcue.ecue, enseignant, 'mecue')
            # print(get_moyenne_ecue(etudiantUE,annee_univ,etudEcue,enseignant,'mecue'))
            nombre_moyEcue += 1
            # print(etudEcue.ecue.libelle)

        # On calcule la moyenne UE de chaque etudiant
        if nombre_moyEcue != 0:
            etud_moyUE = total_moyEcue / nombre_moyEcue
        else:
            etud_moyUE = 0

        if seuil_delib <= 0:
            deliberation = ''
        elif etud_moyUE >= seuil_delib:
            deliberation = 'Admis'
        else:
            deliberation = 'Ajourné'

        # On recupere les infos de l'etudiant
        etudt = Etudiant.objects.get(id=etudiantUE.etudiant.id)
        # On crée une liste de moyenne et d'etudiant
        EtudMoyList.append(etud_moyUE)
        EtudianList.append(etudt)
        DelibList.append(deliberation)
        MentionList.append(get_mention(etud_moyUE))

    # On colle on attribut a chaque etudiant la moyenne
    moyUE_zip = zip(EtudianList, EtudMoyList, DelibList, MentionList)

    context = {
        'zip_list': moyUE_zip,
        'ue': UEs,
        'annee': annee,
    }
    template_path = 'bulletin/resultat_ue_pdf.html'

    # Create a Django response object, and specify content_type as pdf
    response = HttpResponse(content_type='application/pdf')
    # if download
    # response['Content-Disposition'] = 'attachment; filename="report.pdf"'
    # if display
    response['Content-Disposition'] = 'attachment; filename="resultat_UE.pdf"'
    # find the template and render it.
    template = get_template(template_path)
    html = template.render(context)

    # create a pdf
    pisa_status = pisa.CreatePDF(
        html, dest=response, link_callback=link_callback)
    # if error then show some funy view
    if pisa_status.err:
        return HttpResponse('We had some errors <pre>' + html + '</pre>')
    return response


#################################################

# TODO:RESUTAT UE NEW
def resultat_ue_pdf_view_new(request, id):
    # On recupere l'enseignant
    enseignant = Enseignant.objects.get(email=request.user.email)

    EtudMoyList = []
    EtudianList = []
    DelibList = []
    MentionList = []
    annee_univ = Annee.objects.last()

    ##### NEW PARAMS ####
    UE = Ue.objects.get(id=id)
    UE_ecues = Ecue.objects.filter(ue=UE)

    # On recupere tout les etudiant de cette UE
    etudiantUEs = EtudiantUe.objects.filter(parcoursSemestreUe__ue=UE, parcoursSemestreUe__annee=Annee.objects.last())
    # On recupere la deliberation
    try:
        seuil_delib1 = DeliberationUe.objects.get(ue=UE, annee=annee_univ, session__libelle='Session 1')
    except DeliberationUe.DoesNotExist:
        seuil_delib1 = None

    if seuil_delib1:
        seuil_delib = seuil_delib1.note
    else:
        seuil_delib = 0

    # Pour chaque etudiant on calcule la moyenne UE
    for etudiantUE in etudiantUEs:
        # Pour chaque etudiant on calcule la moyenne ECUE
        total_moyEcue = 0
        nombre_moyEcue = 0
        for etudEcue in UE_ecues:
            # print(etudEcue.ecue)
            total_moyEcue += get_moyenne_ecue(etudiantUE.etudiant, annee_univ, etudEcue, enseignant, 'mecue')
            # print(get_moyenne_ecue(etudiantUE,annee_univ,etudEcue,enseignant,'mecue'))
            nombre_moyEcue += 1
            # print(etudEcue.ecue.libelle)

        # On calcule la moyenne UE de chaque etudiant
        if nombre_moyEcue != 0:
            etud_moyUE = total_moyEcue / nombre_moyEcue
        else:
            etud_moyUE = 0

        if seuil_delib <= 0:
            deliberation = ''
        elif etud_moyUE >= seuil_delib:
            deliberation = 'Admis'
        else:
            deliberation = 'Ajourné'

        # On recupere les infos de l'etudiant
        etudt = Etudiant.objects.get(id=etudiantUE.etudiant.id)
        # On crée une liste de moyenne et d'etudiant
        EtudMoyList.append(etud_moyUE)
        EtudianList.append(etudt)
        DelibList.append(deliberation)
        MentionList.append(get_mention(etud_moyUE))

    # On colle on attribut a chaque etudiant la moyenne
    moyUE_zip = zip(EtudianList, EtudMoyList, DelibList, MentionList)

    context = {
        'zip_list': moyUE_zip,
        'ue': UE
    }
    template_path = 'bulletin/resultat_ue_new_pdf.html'

    # Create a Django response object, and specify content_type as pdf
    response = HttpResponse(content_type='application/pdf')
    # if download
    # response['Content-Disposition'] = 'attachment; filename="report.pdf"'
    # if display
    response['Content-Disposition'] = 'attachment;filename="resultat_UE.pdf"'
    # find the template and render it.
    template = get_template(template_path)
    html = template.render(context)

    # create a pdf
    pisa_status = pisa.CreatePDF(
        html, dest=response, link_callback=link_callback)
    # if error then show some funy view
    if pisa_status.err:
        return HttpResponse('We had some errors <pre>' + html + '</pre>')
    return response


#################################################

# TODO:RESUTAT PV
def pv_pdf_view(request, annee, niveau, semestre, ufr):
    # On recupere l'UFR
    # UFR = drUfr.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=get_semestre.niveau.id)

    # ON RECUPERE LES ETUDIANTS
    #etudiants = NiveauEtudiant.objects.filter(annee=get_annee, niveau=get_niveau, etudiant__ufr=UFR).order_by(
    #    'etudiant__nom')

    #etudiant_list = [etudiant.etudiant for etudiant in etudiants]
    etudiant_list = get_etudiant_by_ue_ufr_semestre_list([get_annee,get_niveau,UFR,get_semestre])

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


    # ON RETIRE LES DOUBLONS
    total_credit = sum([get_credit_ue(ue) for ue in ues_semestre])

    # NMBRE DE COLONNE DU TABLEAU
    header_cols = 5 + len(ues_semestre)

    # +++++++++++++++++++++++++++++++
    # CALCUL DE LA MOYENNE DU SEMESTRE
    # Pour chaque etudiant
    moy_etudiant_list = []
    moyUE_etudiant_list = []
    cv_etudiant_list = []
    decision_list = []
    TT_validation = 0  # Total des etudiants ayant validé le semestre
    total_fille_CD = 0
    total_fille_CR = 0
    total_garcon_CD = 0
    total_garcon_CR = 0
    garcon = 0
    fille = 0

    for etudiant in etudiant_list:
        # On RECUPERE LE GENRE DE L'ETUDIANT
        if etudiant.sexe == 'M':
            garcon += 1
        elif etudiant.sexe == 'F':
            fille += 1
        else:
            pass

        # total_moy_ue = 0
        total_moy_ue_CD = 0
        # moySem = 0
        moySem_CD = 0
        cred_valids = 0
        ue_non_valides = 0

        for ue in ues_semestre:
            # MUE = get_etudiant_moyenne_ue3([etudiant,get_annee],ue)
            MUE = get_etudiant_moyenne_ue_session_1(etudiant, [ue, get_annee])
            delibUe = DeliberationUe.objects.filter(ue=ue, annee=get_annee, session__id=1).last()
            sd = 10
            if delibUe:
                sd = delibUe.note

            if MUE >= sd:
                total_moy_ue_CD += MUE * get_credit_ue(ue)
                cred_valids += get_credit_ue(ue)
            elif check_session2_ue(etudiant, [ue, get_annee]) > 0:
                moy_s2 = get_etudiant_session_2_moy_ue(etudiant, [ue, get_annee])

                total_moy_ue_CD += moy_s2 * get_credit_ue(ue)
                if moy_s2 >= sd:
                    cred_valids += get_credit_ue(ue)
                else:
                    ue_non_valides += 1
            else:
                total_moy_ue_CD += MUE * get_credit_ue(ue)
                ue_non_valides += 1

        # Si total crédit = 0 // contrainte division par 0
        if total_credit == 0:
            pass
        else:
            moySem_CD = total_moy_ue_CD / total_credit

            # PAR GENRE
            if etudiant.sexe == 'M':
                total_garcon_CD += moySem_CD
                total_garcon_CR += moySem_CD ** 2
            elif etudiant.sexe == 'F':
                total_fille_CD += moySem_CD
                total_fille_CR += moySem_CD ** 2
            else:
                pass
        # moyenne du semestre
        moy_etudiant_list.append(moySem_CD)
        # crédits validés par l'étudiant
        cv_etudiant_list.append(cred_valids)
        # On calcul le total des moyennes carrées

        # +++++++++++++++++++++++++++++++++++++++++
        # ON FORMULE LA DECISION
        # si tout les crédits sont validés
        if 0 < total_credit == cred_valids:
            decision = 'ADMIS(E)'
            TT_validation += 1
        # si crédits validés à 80% => AUTORISE
        elif total_credit > 0 and (cred_valids / total_credit) * 100 >= 80:
            decision = 'AUTORISE(E)'
            TT_validation += 1
        elif 0 < total_credit and (cred_valids / total_credit) * 100 < 80:
            decision = 'REFUSE(E)'
        else:
            decision = '-------'
        # DECISION FINALE
        decision_list.append(decision)

    # ++++++++++++++++++++++++++++++++++++++++++++++++
    # ON ETABLI LES STATS
    # 1- STATS MOYENNE UE / POUCENTAGE UE VALIDE
    MoyUE = []
    EcarType = []
    Taux_valides = []
    TT_General_Pondere = 0
    for ue in ues_semestre:
        totUE = 0
        TotValides = 0
        TT_Moy_carre = 0  # Total MoyEtudiant au carré
        for etudiant in etudiant_list:
            totUE += get_etudiant_moyenne_ue2(etudiant, [ue, get_annee])
            # Somme des moyennes carrées
            TT_Moy_carre += get_etudiant_moyenne_ue2(etudiant, [ue, get_annee]) ** 2
            # On les etudiants ayant une moyenne UE >=10
            if get_etudiant_moyenne_ue2(etudiant, [ue, get_annee]) >= 10:
                TotValides += 1

        # On calcul la moyenne de l'UE ( S(moyUE)/T(Etudiant) )
        mue = 0
        if len(etudiant_list) > 0:
            mue = totUE / len(etudiant_list)
            EcarType.append(sqrt((TT_Moy_carre / len(etudiant_list)) - (mue ** 2)))
            TT_General_Pondere += (totUE / len(etudiant_list)) * get_credit_ue(ue)
            # On calcul le pourcentage de UE validés ( [T(Etudiant_validés)/T(Etudiant)]*100 )
            Taux_valides.append((TotValides / len(etudiant_list)) * 100)

        MoyUE.append(mue)

    # Zip data
    datas2 = zip(etudiant_list, decision_list)
    valid_Fille = 0
    valid_Garcon = 0
    for etudiant, decison in datas2:
        if etudiant.sexe == 'F':
            if decison == 'AUTORISE(E)' or decison == 'ADMIS(E)':
                valid_Fille += 1
        elif etudiant.sexe == 'M':
            if decison == 'AUTORISE(E)' or decison == 'ADMIS(E)':
                valid_Garcon += 1
        else:
            pass

    datas_etudiant = zip(etudiant_list, moy_etudiant_list, cv_etudiant_list, decision_list, )
    EuAnDataZip = list(zip(ues_semestre, [get_annee for ue in ues_semestre]))
    # # MOYENNE GENERALE UE
    if total_credit > 0:
        MoyGen = TT_General_Pondere / total_credit
    else:
        MoyGen = 0
    # TAUX GENERAL
    if len(etudiant_list) > 0:
        TauxGen = (TT_validation / len(etudiant_list)) * 100
    else:
        TauxGen = 0

    # ECART-TYPE GENERAL
    TT_MoyUE_carre = 0
    for mu in MoyUE:
        TT_MoyUE_carre += mu ** 2

    if len(MoyUE) > 0:
        EcartGen = sqrt(abs(((TT_MoyUE_carre) / len(MoyUE)) - MoyGen ** 2))
    else:
        EcartGen = 0

    # MOYENNE FILLE ET TAUX DE VALIDATION FILLE
    if fille != 0:
        Moy_Fille = total_fille_CD / fille
        Taux_Fille = (valid_Fille / fille) * 100
        # ECART-TYPE FILLE
        Ecart_Type_Fille = sqrt((total_fille_CR / fille) - (Moy_Fille ** 2))
    else:
        Moy_Fille = 0
        Taux_Fille = 0
        Ecart_Type_Fille = 0
    # MOYENNE GARCON ET TAUX DE VALIDATION GARCON
    if garcon != 0:
        Moy_Garcon = total_garcon_CD / garcon
        Taux_Garcon = (valid_Garcon / garcon) * 100
        # ECART-TYPE GARCON
        Ecart_Type_Gar = sqrt((total_garcon_CR / garcon) - (Moy_Garcon ** 2))
    else:
        Moy_Garcon = 0
        Taux_Garcon = 0
        Ecart_Type_Gar = 0

    context = {
        'etudiants': etudiant_list,
        'EuAnDataZip': EuAnDataZip,
        'ues_semestre': ues_semestre,
        'header_cols': header_cols,
        'get_semestre': get_semestre,
        'total_credit': total_credit,
        'datas_etudiant': datas_etudiant,
        'UFR': UFR,
        'get_niveau': get_niveau,
        'get_annee': get_annee,
        'MoyUE': MoyUE,
        'Taux_valides': Taux_valides,
        'EcarType': EcarType,
        'MoyGen': MoyGen,
        'TauxGen': TauxGen,
        'EcartGen': EcartGen,
        'garcon': garcon, 'Moy_Garcon': Moy_Garcon, 'Taux_Garcon': Taux_Garcon, 'Ecart_Type_Gar': Ecart_Type_Gar,
        'fille': fille, 'Moy_Fille': Moy_Fille, 'Taux_Fille': Taux_Fille, 'Ecart_Type_Fille': Ecart_Type_Fille,
    }
    # TEMPLATE HTML DU PDF
    template_path = 'bulletin/pv_pdf.html'

    # Create a Django response object, and specify content_type as pdf
    response = HttpResponse(content_type='application/pdf')
    # if download
    # response['Content-Disposition'] = 'attachment; filename="report.pdf"'
    # if display
    response['Content-Disposition'] = 'filename="PV_' + str(get_semestre) + '_' + str(
        get_niveau) + '_' + str(UFR.code) + '.pdf"'
    # find the template and render it.
    template = get_template(template_path)
    html = template.render(context)

    # create a pdf
    pisa_status = pisa.CreatePDF(
        html, dest=response, link_callback=link_callback)
    # if error then show some funy view
    if pisa_status.err:
        return HttpResponse('We had some errors <pre>' + html + '</pre>')
    return response


############################################

# TODO: JS PDF VIEW
def js_pv_view(request, annee, niveau, semestre, 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=get_semestre.niveau.id)

    # ON RECUPERE LES ETUDIANTS
    etudiant_list = []
    etudiants = etudiant_list = get_etudiant_list([get_annee.id, get_niveau.id, UFR.id])

    # ON RECUPERE LES SEMESTRES DU NIVEAU
    semNiveau = [Semestre.objects.get(id=ue['semestre__id']) for ue in
                 Ue.objects.filter(ufr=UFR, niveau=get_niveau, active=True).values('semestre__id').distinct().order_by(
                     'semestre__id')]
    ues_S1 = get_ue_by_ufr_and_semestre_set([ufr, annee], semNiveau[0].id)
    ues_S2 = get_ue_by_ufr_and_semestre_set([ufr, annee], semNiveau[1].id)
    ues_semestre = get_ue_by_ufr_set(ufr, annee, get_niveau)

    # ****** TOTAL CREDIT ************
    total_credit_S1 = sum([get_credit_ue(ue) for ue in ues_S1])
    total_credit_S2 = sum([get_credit_ue(ue) for ue in ues_S2])
    total_credit = total_credit_S1 + total_credit_S2

    # NMBRE DE COLONNE DU TABLEAU

    if UFR.code == 'MPSI':
        header_colsS2 = 1 + len(ues_S2)
        header_cols = 3 + len(ues_S1)
    else:
        header_colsS2 = 3 + len(ues_S2)
        header_cols = 5 + len(ues_S1)

    # +++++++++++++++++++++++++++++++
    # CALCUL DE LA MOYENNE DU SEMESTRE
    # Pour chaque etudiant
    moy_etudiant_list_S1 = []
    moy_etudiant_list_S2 = []
    cv_etudiant_list_S1 = []
    cv_etudiant_list_S2 = []
    decision_list_S1 = []
    decision_list_S2 = []
    TT_validation_S1 = 0  # Total des etudiants ayant validé le semestre
    TT_validation_S2 = 0  # Total des etudiants ayant validé le semestre
    garcon = 0
    fille = 0
    decision_annuelle = []
    moy_annuelle = []
    ue_valide_annuelle = []
    cv_annuel = []

    decision_list = []
    TT_validation = 0  # Total des etudiants ayant validé le semestre
    total_fille_CD = 0
    total_fille_CR = 0
    total_garcon_CD = 0
    total_garcon_CR = 0

    for etudiant in etudiant_list:

        # ****** MOY S1/S2 **********
        moySem_CD_S1 = 0
        cred_valids_S1 = 0
        ue_non_valides_S1 = 0
        total_moy_ue_CD_S1 = 0
        ue_valide_S1 = 0
        moySem_CD_S2 = 0
        cred_valids_S2 = 0
        ue_non_valides_S2 = 0
        total_moy_ue_CD_S2 = 0
        ue_valide_S2 = 0

        # **** S1 *******
        for ue in ues_S1:
            bonus = get_compens_note([etudiant, get_annee], ue)  # Note de compensation
            MUE = get_etudiant_moyenne_ue3([etudiant, get_annee], ue)
            delibUe = DeliberationUe.objects.filter(ue=ue, annee=get_annee, session__id=1).last()
            sd = 10
            if delibUe:
                sd = delibUe.note

            if MUE >= sd:
                total_moy_ue_CD_S1 += (MUE + bonus) * get_credit_ue(ue)
                cred_valids_S1 += get_credit_ue(ue)

            elif check_session2_ue(etudiant, [ue, get_annee]) > 0:
                moy_s2 = get_etudiant_session_2_moy_ue(etudiant, [ue, get_annee])

                total_moy_ue_CD_S1 += (moy_s2 + bonus) * get_credit_ue(ue)
                if moy_s2 >= sd:
                    cred_valids_S1 += get_credit_ue(ue)
                else:
                    ue_non_valides_S1 += 1
            else:
                total_moy_ue_CD_S1 += (MUE + bonus) * get_credit_ue(ue)
                ue_non_valides_S1 += 1

            if total_credit_S1 == 0:
                pass
            else:
                # 1 on calcul la moyenne
                moySem_CD_S1 = total_moy_ue_CD_S1 / total_credit_S1

        # **** S2 *******
        for ue in ues_S2:
            # bonus = get_compens_note([etudiant, get_annee], ue)  # Note de compensation
            MUE = get_etudiant_moyenne_ue3([etudiant, get_annee], ue)
            delibUe = DeliberationUe.objects.filter(ue=ue, annee=get_annee, session__id=1).last()
            sd = 10
            if delibUe:
                sd = delibUe.note

            if MUE >= sd:
                # total_moy_ue_CD_S2 += (MUE + bonus) * get_credit_ue(ue)
                total_moy_ue_CD_S2 += MUE * get_credit_ue(ue)
                cred_valids_S2 += get_credit_ue(ue)
            elif check_session2_ue(etudiant, [ue, get_annee]) > 0:
                moy_s2 = get_etudiant_session_2_moy_ue(etudiant, [ue, get_annee])

                # total_moy_ue_CD_S2 += (moy_s2 + bonus) * get_credit_ue(ue)
                total_moy_ue_CD_S2 += moy_s2 * get_credit_ue(ue)
                if moy_s2 >= sd:
                    cred_valids_S2 += get_credit_ue(ue)
                else:
                    ue_non_valides_S2 += 1
            else:
                # total_moy_ue_CD_S2 += (MUE + bonus) * get_credit_ue(ue)
                total_moy_ue_CD_S2 += MUE * get_credit_ue(ue)
                ue_non_valides_S2 += 1

            if total_credit_S2 == 0:
                pass
            else:
                # 1 on calcul la moyenne
                moySem_CD_S2 = total_moy_ue_CD_S2 / total_credit_S2

        # moyenne du semestre
        moy_etudiant_list_S1.append(float("{:.2f}".format(moySem_CD_S1)))
        moy_etudiant_list_S2.append(float("{:.2f}".format(moySem_CD_S2)))
        # crédits validés par l'étudiant
        cv_etudiant_list_S1.append(cred_valids_S1)
        cv_etudiant_list_S2.append(cred_valids_S2)
        cv_annuel.append(cred_valids_S1 + cred_valids_S2)
        # On calcul le total des moyennes carrées

        # ******** ON FORMULE LA DECISION S1 ************
        # si tout les crédits sont validés
        if 0 < total_credit_S1 == cred_valids_S1:
            decision_S1 = 'V'
            TT_validation_S1 += 1
        # si crédits validés à 80% => AUTORISE
        elif total_credit_S1 > 0 and (cred_valids_S1 / total_credit_S1) * 100 >= 80:
            decision_S1 = 'A'
            TT_validation_S1 += 1
        elif 0 < total_credit_S1 and (cred_valids_S1 / total_credit_S1) * 100 < 80:
            decision_S1 = 'R'
        else:
            decision_S1 = '-------'
        # DECISION FINALE
        decision_list_S1.append(decision_S1)

        # ******** ON FORMULE LA DECISION S2 ************
        # si tout les crédits sont validés
        if 0 < total_credit_S2 == cred_valids_S2:
            decision_S2 = 'V'
            TT_validation_S2 += 1
        # si crédits validés à 80% => AUTORISE
        elif total_credit_S2 > 0 and (cred_valids_S2 / total_credit_S2) * 100 >= 80:
            decision_S2 = 'A'
            TT_validation_S2 += 1
        elif 0 < total_credit_S2 and (cred_valids_S2 / total_credit_S2) * 100 < 80:
            decision_S2 = 'R'
        else:
            decision_S2 = '-------'
        # DECISION FINALE
        decision_list_S2.append(decision_S2)

        taux_an = ((cred_valids_S1 + cred_valids_S2) / total_credit) * 100

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

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


        decision_annuelle.append(decision)
        # MOYENNE ANNUELLE
        if UFR.code == 'MPSI':
            moy_annuelle.append(float("{:.2f}".format((moySem_CD_S1 + (moySem_CD_S2 * 2)) / 3)))
        else:
            moy_annuelle.append(float("{:.2f}".format((moySem_CD_S1 + moySem_CD_S2) / 2)))
        # TOTAL ANNUEL DE UE VALIDE
        ue_valide_annuelle.append(ue_valide_S1 + ue_valide_S2)

    datas_etudiant = zip(etudiant_list, moy_etudiant_list_S1
                         , cv_etudiant_list_S1, decision_list_S1,
                         moy_etudiant_list_S2, cv_etudiant_list_S2,
                         decision_list_S2, decision_annuelle,
                         moy_annuelle, ue_valide_annuelle, cv_annuel)

    EuAnDataZipS1 = list(zip(ues_S1, [get_annee for ue in ues_semestre]))
    EuAnDataZipS2 = list(zip(ues_S2, [get_annee for ue in ues_semestre]))

    context = {
        'etudiants': etudiant_list,
        'ues_semestre': ues_semestre,
        'EuAnDataZipS1': EuAnDataZipS1,
        'EuAnDataZipS2': EuAnDataZipS2,
        'ues_S2': ues_S2,
        'ues_S1': ues_S1,
        'tota_ue_an': len(ues_S1) + len(ues_S2),
        'header_cols': header_cols,
        'header_colsS2': header_colsS2,
        'get_semestre': get_semestre,
        'total_credit': total_credit,
        'total_credit_S1': total_credit_S1,
        'total_credit_S2': total_credit_S2,
        'datas_etudiant': datas_etudiant,
        'UFR': UFR,
        'get_niveau': get_niveau,
        'get_annee': get_annee,
        'semestre': semNiveau,

    }

    # TEMPLATE HTML DU PDF
    template_path = 'bulletin/js_pdf/JsPdf.html'

    # Create a Django response object, and specify content_type as pdf
    response = HttpResponse(content_type='application/pdf')
    # if download
    # response['Content-Disposition'] = 'attachment; filename="Procès_Verbal.pdf"'
    # if display
    response['Content-Disposition'] = 'attachment; filename="PV FINAL - ' + str(UFR.code) + ' - ' + str(
        get_niveau) + ' | ' + str(get_annee) + '.pdf"'
    # find the template and render it.
    template = get_template(template_path)
    html = template.render(context)

    # create a pdf
    pisa_status = pisa.CreatePDF(
        html, dest=response, link_callback=link_callback)
    # if error then show some funy view
    if pisa_status.err:
        return HttpResponse('We had some errors <pre>' + html + '</pre>')
    return response


##################################################

# TODO: JS PDF VIEW
def pv_annuel_2(request, annee, niveau, semestre, 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=get_semestre.niveau.id)

    # ON RECUPERE LES ETUDIANTS
    etudiant_list = []
    etudiants = etudiant_list = get_etudiant_list([get_annee.id, get_niveau.id, UFR.id])

    # ON RECUPERE LES SEMESTRES DU NIVEAU
    semNiveau = [Semestre.objects.get(id=ue['semestre__id']) for ue in
                 Ue.objects.filter(ufr=UFR, niveau=get_niveau, active=True).values('semestre__id').distinct().order_by(
                     'semestre__id')]
    ues_S1 = get_ue_by_ufr_and_semestre_set([ufr, annee], semNiveau[0].id)
    ues_S2 = get_ue_by_ufr_and_semestre_set([ufr, annee], semNiveau[1].id)
    ues_semestre = get_ue_by_ufr_set(ufr, annee, get_niveau)

    # ****** TOTAL CREDIT ************
    total_credit_S1 = sum([get_credit_ue(ue) for ue in ues_S1])
    total_credit_S2 = sum([get_credit_ue(ue) for ue in ues_S2])
    total_credit = total_credit_S1 + total_credit_S2

    # NMBRE DE COLONNE DU TABLEAU

    if UFR.code == 'MPSI':
        header_colsS2 = 1 + len(ues_S2)
        header_cols = 3 + len(ues_S1)
    else:
        header_colsS2 = 3 + len(ues_S2)
        header_cols = 5 + len(ues_S1)

    # +++++++++++++++++++++++++++++++
    # CALCUL DE LA MOYENNE DU SEMESTRE
    # Pour chaque etudiant
    moy_etudiant_list_S1 = []
    moy_etudiant_list_S2 = []
    cv_etudiant_list_S1 = []
    cv_etudiant_list_S2 = []
    decision_list_S1 = []
    decision_list_S2 = []
    TT_validation_S1 = 0  # Total des etudiants ayant validé le semestre
    TT_validation_S2 = 0  # Total des etudiants ayant validé le semestre
    garcon = 0
    fille = 0
    decision_annuelle = []
    moy_annuelle = []
    ue_valide_annuelle = []
    cv_annuel = []

    decision_list = []
    TT_validation = 0  # Total des etudiants ayant validé le semestre
    total_fille_CD = 0
    total_fille_CR = 0
    total_garcon_CD = 0
    total_garcon_CR = 0

    for etudiant in etudiant_list:

        # ****** MOY S1/S2 **********
        moySem_CD_S1 = 0
        cred_valids_S1 = 0
        ue_non_valides_S1 = 0
        total_moy_ue_CD_S1 = 0
        ue_valide_S1 = 0
        moySem_CD_S2 = 0
        cred_valids_S2 = 0
        ue_non_valides_S2 = 0
        total_moy_ue_CD_S2 = 0
        ue_valide_S2 = 0

        # **** S1 *******
        for ue in ues_S1:
            bonus = get_compens_note([etudiant, get_annee], ue)  # Note de compensation
            MUE = get_etudiant_moyenne_ue3([etudiant, get_annee], ue)
            delibUe = DeliberationUe.objects.filter(ue=ue, annee=get_annee, session__id=1).last()
            sd = 10
            if delibUe:
                sd = delibUe.note

            if MUE >= sd:
                total_moy_ue_CD_S1 += (MUE + bonus) * get_credit_ue(ue)
                cred_valids_S1 += get_credit_ue(ue)

            elif check_session2_ue(etudiant, [ue, get_annee]) > 0:
                moy_s2 = get_etudiant_session_2_moy_ue(etudiant, [ue, get_annee])

                total_moy_ue_CD_S1 += (moy_s2 + bonus) * get_credit_ue(ue)
                if moy_s2 >= sd:
                    cred_valids_S1 += get_credit_ue(ue)
                else:
                    ue_non_valides_S1 += 1
            else:
                total_moy_ue_CD_S1 += (MUE + bonus) * get_credit_ue(ue)
                ue_non_valides_S1 += 1

            if total_credit_S1 == 0:
                pass
            else:
                # 1 on calcul la moyenne
                moySem_CD_S1 = total_moy_ue_CD_S1 / total_credit_S1

        # **** S2 *******
        for ue in ues_S2:
            # bonus = get_compens_note([etudiant, get_annee], ue)  # Note de compensation
            MUE = get_etudiant_moyenne_ue3([etudiant, get_annee], ue)
            delibUe = DeliberationUe.objects.filter(ue=ue, annee=get_annee, session__id=1).last()
            sd = 10
            if delibUe:
                sd = delibUe.note

            if MUE >= sd:
                # total_moy_ue_CD_S2 += (MUE + bonus) * get_credit_ue(ue)
                total_moy_ue_CD_S2 += MUE * get_credit_ue(ue)
                cred_valids_S2 += get_credit_ue(ue)
            elif check_session2_ue(etudiant, [ue, get_annee]) > 0:
                moy_s2 = get_etudiant_session_2_moy_ue(etudiant, [ue, get_annee])

                # total_moy_ue_CD_S2 += (moy_s2 + bonus) * get_credit_ue(ue)
                total_moy_ue_CD_S2 += moy_s2 * get_credit_ue(ue)
                if moy_s2 >= sd:
                    cred_valids_S2 += get_credit_ue(ue)
                else:
                    ue_non_valides_S2 += 1
            else:
                # total_moy_ue_CD_S2 += (MUE + bonus) * get_credit_ue(ue)
                total_moy_ue_CD_S2 += MUE * get_credit_ue(ue)
                ue_non_valides_S2 += 1

            if total_credit_S2 == 0:
                pass
            else:
                # 1 on calcul la moyenne
                moySem_CD_S2 = total_moy_ue_CD_S2 / total_credit_S2

        # moyenne du semestre
        moy_etudiant_list_S1.append(float("{:.2f}".format(moySem_CD_S1)))
        moy_etudiant_list_S2.append(float("{:.2f}".format(moySem_CD_S2)))
        # crédits validés par l'étudiant
        cv_etudiant_list_S1.append(cred_valids_S1)
        cv_etudiant_list_S2.append(cred_valids_S2)
        cv_annuel.append(cred_valids_S1 + cred_valids_S2)
        # On calcul le total des moyennes carrées

        # ******** ON FORMULE LA DECISION S1 ************
        # si tout les crédits sont validés
        if 0 < total_credit_S1 == cred_valids_S1:
            decision_S1 = 'V'
            TT_validation_S1 += 1
        # si crédits validés à 80% => AUTORISE
        elif total_credit_S1 > 0 and (cred_valids_S1 / total_credit_S1) * 100 >= 80:
            decision_S1 = 'A'
            TT_validation_S1 += 1
        elif 0 < total_credit_S1 and (cred_valids_S1 / total_credit_S1) * 100 < 80:
            decision_S1 = 'R'
        else:
            decision_S1 = '-------'
        # DECISION FINALE
        decision_list_S1.append(decision_S1)

        # ******** ON FORMULE LA DECISION S2 ************
        # si tout les crédits sont validés
        if 0 < total_credit_S2 == cred_valids_S2:
            decision_S2 = 'V'
            TT_validation_S2 += 1
        # si crédits validés à 80% => AUTORISE
        elif total_credit_S2 > 0 and (cred_valids_S2 / total_credit_S2) * 100 >= 80:
            decision_S2 = 'A'
            TT_validation_S2 += 1
        elif 0 < total_credit_S2 and (cred_valids_S2 / total_credit_S2) * 100 < 80:
            decision_S2 = 'R'
        else:
            decision_S2 = '-------'
        # DECISION FINALE
        decision_list_S2.append(decision_S2)

        taux_an = ((cred_valids_S1 + cred_valids_S2) / total_credit) * 100


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

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


        decision_annuelle.append(decision)
        # MOYENNE ANNUELLE
        if UFR.code == 'MPSI':
            moy_annuelle.append(float("{:.2f}".format((moySem_CD_S1 + (moySem_CD_S2 * 2)) / 3)))
        else:
            moy_annuelle.append(float("{:.2f}".format((moySem_CD_S1 + moySem_CD_S2) / 2)))
        # TOTAL ANNUEL DE UE VALIDE
        ue_valide_annuelle.append(ue_valide_S1 + ue_valide_S2)

    datas_etudiant = zip(etudiant_list, moy_etudiant_list_S1
                         , cv_etudiant_list_S1, decision_list_S1,
                         moy_etudiant_list_S2, cv_etudiant_list_S2,
                         decision_list_S2, decision_annuelle,
                         moy_annuelle, ue_valide_annuelle, cv_annuel)

    EuAnDataZipS1 = list(zip(ues_S1, [get_annee for ue in ues_semestre]))
    EuAnDataZipS2 = list(zip(ues_S2, [get_annee for ue in ues_semestre]))

    context = {
        'etudiants': etudiant_list,
        'ues_semestre': ues_semestre,
        'EuAnDataZipS1': EuAnDataZipS1,
        'EuAnDataZipS2': EuAnDataZipS2,
        'ues_S2': ues_S2,
        'ues_S1': ues_S1,
        'tota_ue_an': len(ues_S1) + len(ues_S2),
        'header_cols': header_cols,
        'header_colsS2': header_colsS2,
        'get_semestre': get_semestre,
        'total_credit': total_credit,
        'total_credit_S1': total_credit_S1,
        'total_credit_S2': total_credit_S2,
        'datas_etudiant': datas_etudiant,
        'UFR': UFR,
        'get_niveau': get_niveau,
        'get_annee': get_annee,
        'semestre': semNiveau,

    }

    # TEMPLATE HTML DU PDF
    template_path = 'bulletin/js_pdf/pv_annuel_2.html'

    # Create a Django response object, and specify content_type as pdf
    response = HttpResponse(content_type='application/pdf')
    # if download
    # response['Content-Disposition'] = 'attachment; filename="Procès_Verbal.pdf"'
    # if display
    response['Content-Disposition'] = 'attachment; filename="PV FINAL - ' + str(UFR.code) + ' - ' + str(
        get_niveau) + ' | ' + str(get_annee) + '.pdf"'
    # find the template and render it.
    template = get_template(template_path)
    html = template.render(context)

    # create a pdf
    pisa_status = pisa.CreatePDF(
        html, dest=response, link_callback=link_callback)
    # if error then show some funy view
    if pisa_status.err:
        return HttpResponse('We had some errors <pre>' + html + '</pre>')
    return response


############################################

# TODO: GLOBAL STATS PDF VIEW
def global_stat_pv_view(request, annee, niveau, semestre, 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=get_semestre.niveau.id)

    # ON RECUPERE LES ETUDIANTS
    etudiants = get_etudiant_list([get_annee.id, get_niveau.id, UFR.id])

    semNiveau = [Semestre.objects.get(id=ue['semestre__id']) for ue in
                 Ue.objects.filter(ufr=UFR, niveau=get_niveau, active=True).values('semestre__id').distinct().order_by(
                     'semestre__id')]
    ues_S1 = get_ue_by_ufr_and_semestre_set([ufr, annee], semNiveau[0].id)
    ues_S2 = get_ue_by_ufr_and_semestre_set([ufr, annee], semNiveau[1].id)

    ues_semestre2 = []
    for u in ues_S1:
        ues_semestre2.append(u)
    for u in ues_S2:
        ues_semestre2.append(u)
    #ues_semestre = get_ue_by_ufr_set(ufr, annee, get_niveau)
    ues_semestre = ues_semestre2

    #etudiants = get_etudiant_list([get_annee.id, niveau.id, ufr.id])

    cred_valids_S2 = 0
    ue_non_valides_S2 = 0
    total_moy_ue_CD_S2 = 0
    total_credit_S2 = 0
    stat_moy_list = []
    stat_ecart_ue_list = []
    stat_taux_ue_list = []
    moySem_CD_S2 = 0
    garcon = len([etudiant for etudiant in etudiants if etudiant.sexe=='M'])
    fille = len([etudiant for etudiant in etudiants if etudiant.sexe=='F'])
    stat_tot_moy_gen = 0
    total_moyUe_Gar = 0
    total_moyUe_Fil = 0
    total_moyUe = 0
    stat_moy_x_2_Garcon = 0
    stat_moy_x_2_fille = 0
    stat_moy_x_2_gen = 0
    taux_valid_ue_list = []
    et_admin = 0
    et_autorise = 0
    et_refuse = 0

    for ue in ues_semestre:
        stat_total_moyF = 0
        stat_total_moy = 0
        #stat_total_val = 0
        stat_moy_x_2_total = 0
        EcartUe = 0
        stat_tot_garcon = 0
        stat_tot_fille = 0
        total_etud_valid =0

        #print(get_credit_ue(ue))
        for etudiant in etudiants:
            # bonus = get_compens_note([etudiant, get_annee], ue)  # Note de compensation
            MUE = get_etudiant_moyenne_ue3([etudiant, get_annee], ue)
            delibUe = DeliberationUe.objects.filter(ue=ue, annee=get_annee, session__id=1).last()
            sd = 10
            if delibUe:
                sd = delibUe.note

            if MUE >= sd:
                total_moy_ue_CD_S2 += MUE * get_credit_ue(ue)
                stat_total_moy = MUE
                total_etud_valid +=1
            elif check_session2_ue(etudiant, [ue, get_annee]) > 0:
                moy_s2 = get_etudiant_session_2_moy_ue(etudiant, [ue, get_annee])
                total_moy_ue_CD_S2 += moy_s2 * get_credit_ue(ue)
                stat_total_moy = moy_s2
                if moy_s2 >=sd:
                    total_etud_valid += 1
            else:
                total_moy_ue_CD_S2 += MUE * get_credit_ue(ue)
                stat_total_moy = MUE


            # total moyenne par Genre
            if etudiant.sexe == 'M':
                stat_tot_garcon += stat_total_moy
                #stat_moy_x_2_Garcon += stat_total_moy**2
            elif etudiant.sexe == 'F':
                stat_tot_fille += stat_total_moy
                #stat_moy_x_2_fille += stat_total_moy ** 2

            # total des moyennes dechaque etudiant
            stat_total_moyF += stat_total_moy

            # La somme des des carrés des moyennes
            stat_moy_x_2_total += stat_total_moy**2

        # Moyenne de Classe UE & Taux UE
        stat_moy = 0
        TauxUE = 0
        if len(etudiants)>0:
            # moyenne de Classe
            stat_moy = (stat_total_moyF / len(etudiants))
            # Taux Validation UE
            #TauxUE = (stat_total_val /len(etudiants))*100
            # Taux de validation UE
            taux_valid_ue_list.append((total_etud_valid/len(etudiants))*100)

            # Ecart Type Ue
            EcartUe = sqrt((stat_moy_x_2_total/len(etudiants)) - (stat_moy**2))

        if garcon:
            total_moyUe_Gar += (stat_tot_garcon /garcon)
            stat_moy_x_2_Garcon += (stat_tot_garcon /garcon)**2
        if fille:
            total_moyUe_Fil += (stat_tot_fille /fille)
            stat_moy_x_2_fille += (stat_tot_fille /fille)**2



        # liste des moyennes de classe par ue
        stat_tot_moy_gen += stat_moy
        stat_moy_x_2_gen += stat_moy **2
        stat_moy_list.append(stat_moy)
        stat_ecart_ue_list.append(EcartUe)
        #stat_taux_ue_list.append(TauxUE)

    #decis_ls = [decision_annuelle_etudiant_by_annee(etudiant, get_annee) for etudiant in etudiants]
    decis_ls2 = dict((etudiant,decision_annuelle_etudiant_by_annee(etudiant, get_annee)) for etudiant in etudiants)

    et_admin = 0
    G_admin = 0
    F_admin = 0
    et_autorise = 0
    G_autorise = 0
    F_autorise = 0
    et_refuse = 0
    G_refuse = 0
    F_refuse = 0
    for etud,dec in decis_ls2.items():
        if etud.sexe=='M' and dec == 'ADMIS(E)':
            et_admin +=1
            G_admin +=1
        elif etud.sexe=='F' and dec == 'ADMIS(E)':
            et_admin +=1
            F_admin +=1
        elif etud.sexe=='M' and dec == 'AUTORISE(E)':
            et_autorise +=1
            G_autorise +=1
        elif etud.sexe=='F' and dec == 'AUTORISE(E)':
            et_autorise +=1
            F_autorise +=1
        elif etud.sexe=='M' and dec == 'AJOURNE(E)':
            et_refuse +=1
            G_refuse +=1
        elif etud.sexe == 'F' and dec == 'AJOURNE(E)':
            et_refuse += 1
            F_refuse += 1
        else:pass


    #data_zip = zip(stat_moy_list,stat_ecart_ue_list)

#+++++++ STAT GLOBAL ++++++++++++++++
    # Moyenne Garçon & Fille
    MGn =0
    MFe =0
    MoyGen = 0
    EcartGen = 0
    #TauxGen = 0
    Ecart_Type_Gar = 0
    Ecart_Type_Fille = 0
    if len(ues_semestre)>0:
        MGn = total_moyUe_Gar / len(ues_semestre)
        MFe = total_moyUe_Fil / len(ues_semestre)
        MoyGen = stat_tot_moy_gen/len(ues_semestre)
        EcartGen = sqrt((stat_moy_x_2_gen / len(ues_semestre)) - (MoyGen ** 2))
        Ecart_Type_Gar = sqrt((stat_moy_x_2_Garcon / len(ues_semestre)) - (MGn ** 2))
        Ecart_Type_Fille = sqrt((stat_moy_x_2_fille / len(ues_semestre)) - (MFe ** 2))
        #TauxGen = sum(stat_moy_list)/len(ues_semestre)

    taux_Gar_admis = 0
    taux_Gar_autrorise = 0
    taux_Gar_refuse = 0
    if garcon:
        # taux de validation
        taux_Gar_admis = (G_admin/garcon)*100
        taux_Gar_autrorise =(G_autorise/garcon)*100
        taux_Gar_refuse = (G_refuse/garcon)*100

    taux_Fil_admis =0
    taux_Fil_autrorise =0
    taux_Fil_refuse =0
    if fille:
        taux_Fil_admis = (F_admin / fille) * 100
        taux_Fil_autrorise = (F_autorise / fille) * 100
        taux_Fil_refuse = (F_refuse / fille) * 100

    taux_admis =0
    taux_autorise =0
    taux_refuse =0
    if len(etudiants):
        taux_admis = (et_admin/len(etudiants))*100
        taux_autorise = (et_autorise/len(etudiants))*100
        taux_refuse = (et_refuse/len(etudiants))*100


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

    context = {
        'taux_Gar_admis': taux_Gar_admis,
        'taux_Gar_autrorise': taux_Gar_autrorise,
        'taux_Gar_refuse': taux_Gar_refuse,
        'taux_Fil_admis': taux_Fil_admis,
        'taux_Fil_autrorise': taux_Fil_autrorise,
        'taux_Fil_refuse': taux_Fil_refuse,
        'taux_admis': taux_admis,
        'taux_autorise': taux_autorise,
        'taux_refuse': taux_refuse,
        'ues_semestre': ues_semestre,
        'UFR': UFR,
        'get_niveau': get_niveau,
        'get_annee': get_annee,
        'fille': fille,
        'garcon': garcon,
        #'AnNivUfr':[get_annee,get_niveau,UFR],
        #'data_zip':data_zip,
        'etudiants':etudiants,
        'MGn':MGn,
        'MFe':MFe,
        'MoyGen':MoyGen,
        'EcartGen':EcartGen,
        #'TauxGen':TauxGen,
        'Ecart_Type_Gar':Ecart_Type_Gar,
        'Ecart_Type_Fille':Ecart_Type_Fille,
        'stat_ecart_ue_list':stat_ecart_ue_list,
        'stat_moy_list':stat_moy_list,
        #'stat_taux_ue_list':stat_taux_ue_list,
        'taux_valid_ue_list':taux_valid_ue_list,
        'admis':et_admin,
        'G_admis':G_admin,
        'F_admis':F_admin,
        'autorises':et_autorise,
        'G_autorise':G_autorise,
        'F_autorise':F_autorise,
        'refuses':et_refuse,
        'G_refuse':G_refuse,
        'F_refuse':F_refuse,

    }

    # TEMPLATE HTML DU PDF
    template_path = 'bulletin/js_pdf/stats_global.html'

    # Create a Django response object, and specify content_type as pdf
    response = HttpResponse(content_type='application/pdf')
    # if download
    # response['Content-Disposition'] = 'attachment; filename="Procès_Verbal.pdf"'
    # if display
    response['Content-Disposition'] = 'attachment; filename="STATS - ' + str(UFR.code) + ' - ' + str(
        get_niveau) + ' | ' + str(get_annee) + '.pdf"'
    # find the template and render it.
    template = get_template(template_path)
    html = template.render(context)

    # create a pdf
    pisa_status = pisa.CreatePDF(
        html, dest=response, link_callback=link_callback)
    # if error then show some funy view
    if pisa_status.err:
        return HttpResponse('We had some errors <pre>' + html + '</pre>')
    return response


#################################################

# TODO:RESUTAT PV
def refuses_pdf_view(request, annee, niveau, semestre, ufr):
    # On recupere l'UFR
    # UFR = drUfr.ufr
    UFR = Ufr.objects.get(id=ufr)
    ############################################

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

    # ON RECUPERE LES ETUDIANTS
    etudiants = NiveauEtudiant.objects.filter(annee=get_annee, niveau=get_niveau, etudiant__ufr=UFR)
    etudiant_list = [etudiant.etudiant for etudiant in etudiants]

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

    total_credit = sum([get_credit_ue(ue) for ue in ues_semestre])

    # NMBRE DE COLONNE DU TABLEAU
    header_cols = 5 + len(ues_semestre)

    # +++++++++++++++++++++++++++++++
    # CALCUL DE LA MOYENNE DU SEMESTRE
    # Pour chaque etudiant
    moy_etudiant_list = []
    moyUE_etudiant_list = []
    cv_etudiant_list = []
    decision_list = []
    TT_validation = 0  # Total des etudiants ayant validé le semestre
    total_fille_CD = 0
    total_fille_CR = 0
    total_garcon_CD = 0
    total_garcon_CR = 0
    garcon = 0
    fille = 0

    for etudiant in etudiant_list:
        # On RECUPERE LE GENRE DE L'ETUDIANT
        if etudiant.sexe == 'M':
            garcon += 1
        elif etudiant.sexe == 'F':
            fille += 1
        else:
            pass

        # total_moy_ue = 0
        total_moy_ue_CD = 0
        # moySem = 0
        moySem_CD = 0
        cred_valids = 0
        ue_non_valides = 0
        for ue in ues_semestre:
            # total_moy_ue += get_etudiant_moyenne_ue(etudiant,ue.ue.id)
            total_moy_ue_CD += get_etudiant_moyenne_ue(etudiant, ue.ue.id) * get_credit_ue(ue.ue)

            if get_etudiant_moyenne_ue(etudiant, ue.ue.id) >= 10:
                cred_valids += get_credit_ue(ue.ue)
            else:
                ue_non_valides += 1

        # Si total crédit = 0 // contrainte division par 0
        if total_credit == 0:
            pass
        else:
            # 1 on calcul la moyenne (sans le nombre de crédit)
            # moySem = total_moy_ue/len(ues_semestre)
            moySem_CD = total_moy_ue_CD / total_credit

            # PAR GENRE
            if etudiant.sexe == 'M':
                total_garcon_CD += moySem_CD
                total_garcon_CR += moySem_CD ** 2
            elif etudiant.sexe == 'F':
                total_fille_CD += moySem_CD
                total_fille_CR += moySem_CD ** 2
            else:
                pass
        # moyenne du semestre
        moy_etudiant_list.append(moySem_CD)
        # crédits validés par l'étudiant
        cv_etudiant_list.append(cred_valids)
        # On calcul le total des moyennes carrées

        # +++++++++++++++++++++++++++++++++++++++++
        # ON FORMULE LA DECISION
        # si tout les crédits sont validés
        if 0 < total_credit == cred_valids:
            decision = 'ADMIS(E)'
            TT_validation += 1
        # si crédits validés à 80% => AUTORISE
        elif total_credit > 0 and (cred_valids / total_credit) * 100 >= 80:
            decision = 'AUTORISE(E)'
            TT_validation += 1
        elif 0 < total_credit and (cred_valids / total_credit) * 100 < 80:
            decision = 'REFUSE(E)'
        else:
            decision = '-------'
        # DECISION FINALE
        decision_list.append(decision)

    # Zip data
    datas2 = zip(etudiant_list, decision_list)
    valid_Fille = 0
    valid_Garcon = 0
    for etudiant, decison in datas2:
        if etudiant.sexe == 'F':
            if decison == 'AUTORISE(E)' or decison == 'ADMIS(E)':
                valid_Fille += 1
        elif etudiant.sexe == 'M':
            if decison == 'AUTORISE(E)' or decison == 'ADMIS(E)':
                valid_Garcon += 1
        else:
            pass

    datas_etudiant = zip(etudiant_list, moy_etudiant_list, cv_etudiant_list, decision_list)

    context = {
        'etudiants': etudiant_list,
        'ues_semestre': ues_semestre,
        'header_cols': header_cols,
        'get_semestre': get_semestre,
        'total_credit': total_credit,
        'datas_etudiant': datas_etudiant,
        'UFR': UFR,
        'get_niveau': get_niveau,
        'get_annee': get_annee,
        'garcon': garcon,
        # 'Moy_Garcon': Moy_Garcon, 'Taux_Garcon': Taux_Garcon, 'Ecart_Type_Gar': Ecart_Type_Gar,
        'fille': fille,
        # 'Moy_Fille': Moy_Fille, 'Taux_Fille': Taux_Fille, 'Ecart_Type_Fille': Ecart_Type_Fille,
    }
    # TEMPLATE HTML DU PDF
    template_path = 'bulletin/refuses_list_pdf.html'

    # Create a Django response object, and specify content_type as pdf
    response = HttpResponse(content_type='application/pdf')
    # if download
    # response['Content-Disposition'] = 'attachment; filename="report.pdf"'
    # if display
    response['Content-Disposition'] = 'attachment;filename="Procès_Verbal.pdf"'
    # find the template and render it.
    template = get_template(template_path)
    html = template.render(context)

    # create a pdf
    pisa_status = pisa.CreatePDF(
        html, dest=response, link_callback=link_callback)
    # if error then show some funy view
    if pisa_status.err:
        return HttpResponse('We had some errors <pre>' + html + '</pre>')
    return response


#################################################

# TODO:REFUSES PAR UE
def refuses_ue_pdf_view(request, annee, niveau, semestre, ufr, ue):
    # On recupere l'UFR
    # UFR = drUfr.ufr
    UFR = Ufr.objects.get(id=ufr)
    ############################################

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

    # ON RECUPERE LES ETUDIANTS
    etudiants = get_etudiant_list([annee, niveau, ufr])
    # etudiants = EtudiantUe.objects.filter(parcoursSemestreUe__ue__ufr=UFR, parcoursSemestreUe__annee=get_annee).order_by('etudiant__nom')
    etudiant_list = []
    ue_list = []

    # ON RECUPERE LA DELIBERATION DE L'UE
    deliberation = DeliberationUe.objects.filter(annee=get_annee, ue=get_ue, session__id=1).last()

    deliberation_note = 0.0
    if deliberation:
        deliberation_note = deliberation.note

    etudiant_list = [etd for etd in etudiants if
                     get_etudiant_moyenne_ue_session_1(etd, [get_ue, get_annee]) < deliberation_note]

    context = {
        'etudiants': etudiant_list,
        'UFR': UFR,
        'UeAnneeData': [get_ue, get_annee],
        'get_niveau': get_niveau,
        'get_annee': get_annee,
        'get_ue': get_ue,
        'get_semestre': get_semestre,
    }
    # TEMPLATE HTML DU PDF
    template_path = 'bulletin/refuses_ue_pdf.html'

    # Create a Django response object, and specify content_type as pdf
    response = HttpResponse(content_type='application/pdf')
    # if download
    # response['Content-Disposition'] = 'attachment; filename="REFUSES_UE_'+str(get_ue.code)+'.pdf"'
    # if display
    response['Content-Disposition'] = 'attachment;filename="REFUSES_UE_' + str(get_ue.code) + '.pdf"'
    # find the template and render it.
    template = get_template(template_path)
    html = template.render(context)

    # create a pdf
    pisa_status = pisa.CreatePDF(
        html, dest=response, link_callback=link_callback)
    # if error then show some funy view
    if pisa_status.err:
        return HttpResponse('We had some errors <pre>' + html + '</pre>')
    return response


#################################################

# TODO:REFUSES PAR UE
def refuses_ue_annuel_pdf(request, annee, niveau, semestre, ufr, ue):
    # On recupere l'UFR
    # UFR = drUfr.ufr
    UFR = Ufr.objects.get(id=ufr)
    ############################################

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

    # ON RECUPERE LES ETUDIANTS
    etudiants = get_etudiant_list([annee, niveau, ufr])

    # ON RECUPERE LA DELIBERATION DE L'UE
    deliberation = DeliberationUe.objects.filter(annee=get_annee, ue=get_ue, session__id=1).last()

    deliberation_note = 0.0
    if deliberation:
        deliberation_note = deliberation.note

    etudiant_list = [etd for etd in etudiants if
                     get_etudiant_moyenne_ue_session_1(etd, [get_ue, get_annee]) < deliberation_note and get_etudiant_session_2_moy_ue(etd, [get_ue, get_annee]) < deliberation_note]

    context = {
        'etudiants': etudiant_list,
        'UFR': UFR,
        'UeAnneeData': [get_ue, get_annee],
        'get_niveau': get_niveau,
        'get_annee': get_annee,
        'get_ue': get_ue,
        'get_semestre': get_semestre,
    }
    # TEMPLATE HTML DU PDF
    template_path = 'bulletin/refuses_ue_annuel_pdf.html'

    # Create a Django response object, and specify content_type as pdf
    response = HttpResponse(content_type='application/pdf')
    # if download
    # response['Content-Disposition'] = 'attachment; filename="REFUSES_UE_'+str(get_ue.code)+'.pdf"'
    # if display
    response['Content-Disposition'] = 'attachment; filename="REFUSES_UE_' + str(get_ue.code) + '.pdf"'
    # find the template and render it.
    template = get_template(template_path)
    html = template.render(context)

    # create a pdf
    pisa_status = pisa.CreatePDF(
        html, dest=response, link_callback=link_callback)
    # if error then show some funy view
    if pisa_status.err:
        return HttpResponse('We had some errors <pre>' + html + '</pre>')
    return response


#################################################

# TODO:VALIDES PAR UE
def valides_ue_pdf_view(request, annee, niveau, semestre, ufr, ue):
    # On recupere l'UFR
    # UFR = drUfr.ufr
    UFR = Ufr.objects.get(id=ufr)
    ############################################

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

    # ON RECUPERE LES ETUDIANTS
    etudiants = get_etudiant_list([annee, niveau, ufr])
    # etudiants = EtudiantUe.objects.filter(parcoursSemestreUe__ue__ufr=UFR, parcoursSemestreUe__annee=get_annee).order_by('etudiant__nom')
    etudiant_list = []
    ue_list = []

    # ON RECUPERE LA DELIBERATION DE L'UE
    deliberation = DeliberationUe.objects.filter(annee=get_annee, ue=get_ue, session__id=1).last()

    deliberation_note = 0.0
    if deliberation:
        deliberation_note = deliberation.note

    etudiant_list = [etd for etd in etudiants if
                     get_etudiant_moyenne_ue_session_1(etd, [get_ue, get_annee]) >= deliberation_note]

    context = {
        'etudiants': etudiant_list,
        'UFR': UFR,
        'UeAnneeData': [get_ue, get_annee],
        'get_niveau': get_niveau,
        'get_annee': get_annee,
        'get_ue': get_ue,
        'get_semestre': get_semestre,
        'deliberation': deliberation,
    }
    # TEMPLATE HTML DU PDF
    template_path = 'bulletin/valides_ue_pdf.html'

    # Create a Django response object, and specify content_type as pdf
    response = HttpResponse(content_type='application/pdf')
    # if download
    # response['Content-Disposition'] = 'attachment; filename="VALIDES_UE_'+str(get_ue.code)+'.pdf"'
    # if display
    response['Content-Disposition'] = 'attachment;filename="VALIDES_UE_' + str(get_ue.code) + '.pdf"'
    # find the template and render it.
    template = get_template(template_path)
    html = template.render(context)

    # create a pdf
    pisa_status = pisa.CreatePDF(
        html, dest=response, link_callback=link_callback)
    # if error then show some funy view
    if pisa_status.err:
        return HttpResponse('We had some errors <pre>' + html + '</pre>')
    return response


#################################################

# TODO:VALIDES PAR ECUE
def valides_ecue_pdf_view(request, annee, niveau, semestre, ufr, ecue):
    UFR = Ufr.objects.get(id=ufr)
    ############################################

    # ON RECUPERE LES INFOS DES PARAMETRES
    get_ecue = Ecue.objects.get(id=ecue)
    get_ue = get_ecue.ue
    get_annee = Annee.objects.get(id=annee)
    get_niveau = Niveau.objects.get(id=niveau)
    get_semestre = Semestre.objects.get(id=semestre)

    # ON RECUPERE LES ETUDIANTS
    etudiants = get_etudiant_list([annee, niveau, ufr])

    # ON RECUPERE LA DELIBERATION DE L'UE
    deliberation = Deliberation.objects.filter(annee=get_annee, ecue=get_ecue, session__id=1).last()

    deliberation_note = 0.0
    if deliberation:
        deliberation_note = deliberation.note

    etudiant_list = [etd for etd in etudiants if
                     get_etudiant_moyenne_ecue_session_1([etd.id, get_annee.id],
                                                         get_ecue.id) >= deliberation_note and deliberation_note > 0]

    context = {
        'etudiants': etudiant_list,
        'UFR': UFR,
        'UeAnneeData': [ecue, annee],
        'get_niveau': get_niveau,
        'get_annee': get_annee,
        'get_ue': get_ue,
        'get_ecue': get_ecue,
        'get_semestre': get_semestre,
        'deliberation': deliberation,
    }
    # TEMPLATE HTML DU PDF
    template_path = 'bulletin/valides_ecue_pdf.html'

    # Create a Django response object, and specify content_type as pdf
    response = HttpResponse(content_type='application/pdf')
    # if download
    # response['Content-Disposition'] = 'attachment; filename="VALIDES_'+str(get_ecue.code)+'.pdf"'
    # if display
    response['Content-Disposition'] = 'attachment;filename="VALIDES_' + str(get_ecue.code) + '.pdf"'
    # find the template and render it.
    template = get_template(template_path)
    html = template.render(context)

    # create a pdf
    pisa_status = pisa.CreatePDF(
        html, dest=response, link_callback=link_callback)
    # if error then show some funy view
    if pisa_status.err:
        return HttpResponse('We had some errors <pre>' + html + '</pre>')
    return response


#################################################

# TODO:REFUSES PAR ECUE
def refuses_ecue_pdf_view(request, annee, niveau, semestre, ufr, ecue):
    UFR = Ufr.objects.get(id=ufr)
    ############################################

    # ON RECUPERE LES INFOS DES PARAMETRES
    get_ecue = Ecue.objects.get(id=ecue)
    get_ue = get_ecue.ue
    get_annee = Annee.objects.get(id=annee)
    get_niveau = Niveau.objects.get(id=niveau)
    get_semestre = Semestre.objects.get(id=semestre)

    # ON RECUPERE LES ETUDIANTS
    etudiants = get_etudiant_list([annee, niveau, ufr])

    # ON RECUPERE LA DELIBERATION DE L'UE
    deliberation = Deliberation.objects.filter(annee=get_annee, ecue=get_ecue, session__id=1).last()

    deliberation_note = 0.0
    if deliberation:
        deliberation_note = deliberation.note

    etudiant_list = [etd for etd in etudiants if
                     get_etudiant_moyenne_ecue_session_1([etd.id, get_annee.id], get_ecue.id) < deliberation_note]

    context = {
        'etudiants': etudiant_list,
        'UFR': UFR,
        'UeAnneeData': [ecue, annee],
        'get_niveau': get_niveau,
        'get_annee': get_annee,
        'get_ue': get_ue,
        'get_ecue': get_ecue,
        'get_semestre': get_semestre,
        'deliberation': deliberation,
    }
    # TEMPLATE HTML DU PDF
    template_path = 'bulletin/refuses_ecue_pdf.html'

    # Create a Django response object, and specify content_type as pdf
    response = HttpResponse(content_type='application/pdf')
    # if download
    # response['Content-Disposition'] = 'attachment; filename="REFUSES_'+str(get_ecue.code)+'.pdf"'
    # if display
    response['Content-Disposition'] = 'attachment;filename="REFUSES_' + str(get_ecue.code) + '.pdf"'
    # find the template and render it.
    template = get_template(template_path)
    html = template.render(context)

    # create a pdf
    pisa_status = pisa.CreatePDF(
        html, dest=response, link_callback=link_callback)
    # if error then show some funy view
    if pisa_status.err:
        return HttpResponse('We had some errors <pre>' + html + '</pre>')
    return response


#################################################

# TODO:REFUSES PAR ECUE
def syllabus_ecue_pdf(request, id):
    # ON RECUPERE L'ECUE
    ecue = Ecue.objects.get(id=id)

    # ON RECUPERE LE SYLLABUS
    syllabus = SyllabusEcue.objects.filter(ecue=ecue).last()

    context = {
        'ecue': ecue,
        'syllabus': syllabus,
    }
    # TEMPLATE HTML DU PDF
    template_path = 'bulletin/syllabus_ecue_pdf.html'

    # Create a Django response object, and specify content_type as pdf
    response = HttpResponse(content_type='application/pdf')
    # if download
    # response['Content-Disposition'] = 'attachment; filename="SYLLABUS_ECUE_'+str(ecue.code)+'.pdf"'
    # if display
    response['Content-Disposition'] = 'attachment;filename="SYLLABUS_ECUE_' + str(ecue.code) + '.pdf"'
    # find the template and render it.
    template = get_template(template_path)
    html = template.render(context)

    # create a pdf
    pisa_status = pisa.CreatePDF(
        html, dest=response, link_callback=link_callback)
    # if error then show some funy view
    if pisa_status.err:
        return HttpResponse('We had some errors <pre>' + html + '</pre>')
    return response


#################################################

# TODO: SEANCE DR UFR
def dr_ufr_seance_pdf(request, ufr, ens, ecue, status, debut, fin):
    # ROLE
    user = Enseignant.objects.get(email=request.user.email)

    # ON RECUPERE L'UFR/ SES ECUES/ LES NIVEAUX/ LE PROGRAMME
    ############ new Enseignant Ufr ############
    # On recupere les infos du DR
    annee = Annee.objects.last()
    drUfr = EnseignantUfr.objects.filter(annee=annee, enseignant=user).last()
    # On recupere l'UFR
    UFR = None
    if drUfr:
        UFR = drUfr.ufr
    ############################################

    # ON CONTROLE LES DATE DE DEBUT ET DE FIN
    if debut > fin:
        temp = debut
        debut = fin
        fin = temp

    seances = None

    if ecue == 'tous' and ens == 'tous' and status == 'tous':
        seances = SeanceCours.objects.filter(ecue__ue__ufr__id=ufr, date__gte=debut, date__lte=fin).order_by('-date')

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

    elif ecue != 'tous' and ens == 'tous' and status == 'tous':
        seances = SeanceCours.objects.filter(ecue__ue__ufr__id=ufr, ecue=Ecue.objects.get(id=ecue), 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__id=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__id=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__id=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__id=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__id=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__id=ufr, cue=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__id=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__id=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__id=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

    ens_obj = None
    if ens != 'tous':
        ens_obj = Enseignant.objects.get(id=ens)
    ecue_obj = None
    if ecue != 'tous':
        ecue_obj = Ecue.objects.get(id=ecue)

    context = {
        'UFR': UFR,
        'ecue_obj': ecue_obj,
        'ens_obj': ens_obj,
        'debut': debut,
        'fin': fin,
        'ens': ens,
        'ecue': ecue,
        'status': status,
        'seances': seances,
        'user': user,
    }
    # TEMPLATE HTML DU PDF
    template_path = 'bulletin/dr_ufr_seance_pdf.html'

    # Create a Django response object, and specify content_type as pdf
    response = HttpResponse(content_type='application/pdf')
    # if download
    # response['Content-Disposition'] = 'attachment; filename="SYLLABUS_ECUE_'+str(ecue.code)+'.pdf"'
    # if display
    response['Content-Disposition'] = 'attachment; filename="SEANCES DU ' + str(debut) + ' AU ' + str(fin) + '.pdf"'
    # find the template and render it.
    template = get_template(template_path)
    html = template.render(context)

    # create a pdf
    pisa_status = pisa.CreatePDF(
        html, dest=response, link_callback=link_callback)
    # if error then show some funy view
    if pisa_status.err:
        return HttpResponse('We had some errors <pre>' + html + '</pre>')
    return response