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
from BasicData.templatetags.custom_tag_obj import get_etudiant_list
from .forms import *
from math import *
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:VALIDES SEMESTRE 1 SESSION 1
def valides_sem_sess_1_pdf_view(request,annee,semestre,ufr,arg):
    # 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)

    etudiant_list = [etudiant.etudiant for etudiant in etudiants]

    # ON RECUPERE LES UE DU SEMESTRE
    ues_semestre = Ue.objects.filter(ufr=UFR,niveau=get_niveau,semestre=get_semestre,active=True).order_by('libelle')
    total_credit = sum([get_credit_ue(ue) for ue in 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

    etudiant_list2 =[]
    moy_etudiant_list2 = []
    decision_list2 = []
    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)
            delibUe = DeliberationUe.objects.filter(ue=ue, annee=get_annee, session__id=1).last()

            if delibUe and MUE >= delibUe.note:
                total_moy_ue_CD += get_etudiant_moyenne_ue3([etudiant, get_annee], ue) * get_credit_ue(ue)
                cred_valids += get_credit_ue(ue)
            else:
                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)

        if arg == 'v' and decision == 'ADMIS(E)' or decision == 'AUTORISE(E)':
            etudiant_list2.append(etudiant)
            moy_etudiant_list2.append(moySem_CD)
            decision_list2.append(decision)
        elif arg == 'r' and decision == 'REFUSE(E)':
            etudiant_list2.append(etudiant)
            moy_etudiant_list2.append(moySem_CD)
            decision_list2.append(decision)
        else:pass

    #### LIBELLE DU PDF EN FONCTION DE TYPE ####
    title =''
    libelle =''
    if arg == 'v':
        title = 'VALIDES'
        libelle = 'LISTE DES ETUDIANTS AYANT VALIDER LE SEMESTRE EN SESSION 1'
    else:
        title = 'REFUSES'
        libelle = "LISTE DES ETUDIANTS N'AYANT VALIDER LE SEMESTRE EN SESSION 1"

    # ++++++++++++++++++++++++++++++++++++++++++++++++
    datas_etudiant2 = zip(etudiant_list2, moy_etudiant_list2, decision_list2)
    EuAnDataZip = list(zip(ues_semestre, [get_annee for ue in ues_semestre]))


    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,
        'datas_etudiant2': datas_etudiant2,
        'UFR': UFR,
        'get_niveau': get_niveau,
        'get_annee': get_annee,
        'title': title,
        'libelle': libelle,
    }
    # TEMPLATE HTML DU PDF
    template_path = 'bulletin/valides_semestre_session_1_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="'+str(title)+'_SESSION_1_'+ 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:EVALUATION ETUDIANTS SESSION 2 ECUE
def note_ecue_session_2_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': [get_ecue, get_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/note_ecue_session_2_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'] = 'filename="EVALUATION_SESSION_2_'+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:MOYENNE UE SESSION 2
def moyenne_ue_sess_2_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]

    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/moyenne_sess_2_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'] = 'filename="SESSION_2_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
