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
import csv

from BasicData.models import Etudiant, Document, Annee, NiveauEtudiant, Semestre, Enseignant, Niveau
from BasicData.templatetags.custom_tag_obj import get_niveau_etudiant
from Scolarite.models import AgentScolarite


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:DOCUMENTS
def document_pdf_view(request, id,typdoc):
    # ON RECUPERE LES INFOS DU CANDIDAT
    etudiant = Etudiant.objects.get(id=id)
    document = Document.objects.filter(typedoc__id=typdoc,etudiant=etudiant).last()

    context = {
        'etudiant':etudiant,
        'document':document,
    }
    # TEMPLATE HTML DU PDF
    template_path = 'scolarite/pdf/document_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="CANDIDATURE-'+str(candidat.nc)+'.pdf"'
    # if display
    if document:
        response['Content-Disposition'] = 'filename="DOC-' + str(document.typedoc.libelle).upper() + '-' + str(etudiant.nce) + '.pdf"'
    else:
        response['Content-Disposition'] = 'filename="DOC-' + str(
            etudiant.nce) + '.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: FICHES ET RECUS
def fiches_et_recus_pdf(request, id):
    # ON RECUPERE LES INFOS DU CANDIDAT
    etudiant = Etudiant.objects.get(id=id)
    #candidature = Candidature.objects.get(id=id)

    context = {
        'etudiant':etudiant,
        'annee':Annee.objects.last()
    }
    # TEMPLATE HTML DU PDF
    template_path = 'scolarite/pdf/fiches_et_recus_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="CANDIDATURE-'+str(candidat.nc)+'.pdf"'
    # if display
    response['Content-Disposition'] = ' filename="INSCRIPTION-' + str(etudiant.nce) + '.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: FICHES ET RECUS
def fiche_scolarite(request, id):
    # ON RECUPERE LES INFOS DU CANDIDAT
    etudiant = Etudiant.objects.get(id=id)
    #candidature = Candidature.objects.get(id=id)

    context = {
        'etudiant':etudiant,
        'annee':Annee.objects.all()
    }
    # TEMPLATE HTML DU PDF
    template_path = 'scolarite/pdf/fiche_scolarite.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="CANDIDATURE-'+str(candidat.nc)+'.pdf"'
    # if display
    response['Content-Disposition'] = ' filename="DOSSIER-' + str(etudiant.nce) + '.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: RELEVE DE NOTE ANNUEL
def releve_de_note(request,id,an):
    etudiant = Etudiant.objects.get(id=id)
    annee = Annee.objects.get(id=an)

    # ON RECUPERE LE NIVEAU DE L'ETUDIANT
    nivEtud = NiveauEtudiant.objects.filter(annee=an,etudiant=etudiant).last()
    semestres = None
    if nivEtud:
        semestres = Semestre.objects.filter(niveau=nivEtud.niveau).order_by('libelle')

    # USER CHECK
    ags = AgentScolarite.objects.filter(email=request.user.email).last()
    user = Enseignant.objects.filter(email=request.user.email).last()

    context = {
        'etudiant':etudiant,
        'annee':annee,
        'nivEtud':get_niveau_etudiant(etudiant,annee),
        'semestres':semestres,
        'ufrAn':[etudiant.ufr.id,annee.id],
        'etudAn':[etudiant,annee],
        'ags':ags,
    }
    # TEMPLATE HTML DU PDF
    template_path = 'scolarite/pdf/releve_de_note_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="CANDIDATURE-'+str(candidat.nc)+'.pdf"'
    # if display
    response['Content-Disposition'] = 'attachment; filename="RELEVE_DE_NOTE-' + str(etudiant.nce) + '.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: RELEVE DE NOTE
def releve_de_note_semestre(request,id,an,sem):
    etudiant = Etudiant.objects.get(id=id)
    annee = Annee.objects.get(id=an)
    #semestre = Semestre.objects.get(id=sem)
    semestre = Semestre.objects.get(id=sem)

    # USER CHECK
    ags = AgentScolarite.objects.filter(email=request.user.email).last()
    user = Enseignant.objects.filter(email=request.user.email).last()

    # ON RECUPERE LE NIVEAU DE L'ETUDIANT
    nivEtud = NiveauEtudiant.objects.filter(annee=an,etudiant=etudiant).last()
    semestres = None
    if nivEtud:
        semestres = Semestre.objects.filter(niveau=nivEtud.niveau).order_by('libelle')
        #semestre = Semestre.objects.filter(niveau=nivEtud.niveau).order_by('libelle').first()

    context = {
        'etudiant':etudiant,
        'annee':annee,
        'semestre':semestre,
        'nivEtud':get_niveau_etudiant(etudiant,annee),
        'semestres':semestres,
        'ufrAn':[etudiant.ufr.id,annee.id],
        'etudAn':[etudiant,annee],
        'etudAn_id':[etudiant,annee.id],
        'ags':ags,
    }
    # TEMPLATE HTML DU PDF
    template_path = 'scolarite/pdf/releve_de_note_semestre_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="CANDIDATURE-'+str(candidat.nc)+'.pdf"'
    # if display
    response['Content-Disposition'] = ' filename="RELEVE_DE_NOTE_SEMESTRE-' + str(etudiant.nce) + '.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: RELEVE DE NOTE ANNUEL
def certificat_scolarite(request,id,an):
    etudiant = Etudiant.objects.get(id=id)
    annee = Annee.objects.get(id=an)

    prev_year = Annee.objects.filter(id__lt=an).order_by('id').first()

    # ON RECUPERE LE NIVEAU DE L'ETUDIANT
    nivEtud = NiveauEtudiant.objects.filter(annee=an,etudiant=etudiant).last()
    semestres = None
    niv = None
    prev_niv = None
    if nivEtud:
        semestres = Semestre.objects.filter(niveau=nivEtud.niveau).order_by('libelle')
        nivsplit = nivEtud.niveau.libelle.split(' ')
        niv = str(nivsplit[0][0].upper())+str(nivsplit[1])

        prev_niv = Niveau.objects.filter(id__lt=nivEtud.niveau.id).order_by('id').first()
        #print(prev_niv)


    # USER CHECK
    ags = AgentScolarite.objects.filter(email=request.user.email).last()
    user = Enseignant.objects.filter(email=request.user.email).last()

    context = {
        'etudiant':etudiant,
        'annee':annee,
        'nivEtud':get_niveau_etudiant(etudiant,annee),
        'semestres':semestres,
        'ufrAn':[etudiant.ufr.id,annee.id],
        'etudAn':[etudiant,annee],
        'ags':ags,
        'niv':niv,
        'prev_year':prev_year,
        'prev_niv':prev_niv,
    }
    # TEMPLATE HTML DU PDF
    template_path = 'scolarite/pdf/certificat_scolarite_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="CANDIDATURE-'+str(candidat.nc)+'.pdf"'
    # if display
    response['Content-Disposition'] = 'attachment;filename="CERTIFICAT DE SCOLARITE -' + str(etudiant.nce) + '.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