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 concours.models import Candidat, Annee, TypeConcours, Candidature, Document, Paiement
from concours.templatetags.custom_tag import get_moyenne_ecrit, get_deliberation_provisoire


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: FICHES ET RECUS
def fiches_et_recus_pdf(request, id):
    # ON RECUPERE LES INFOS DU CANDIDAT
    candidat = Candidat.objects.filter(email=request.user.email).last()
    candidature = Candidature.objects.get(id=id)

    context = {
        'candidat':candidat,
        'candidature':candidature,
    }
    # TEMPLATE HTML DU PDF
    template_path = '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
    if candidat:
        response['Content-Disposition'] = 'attachment; filename="CANDIDATURE-'+str(candidature.candidat.nc)+'.pdf"'
    else:
        response['Content-Disposition'] = ' filename="CANDIDATURE-' + str(candidature.candidat.nc) + '.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:DOCUMENTS
def document_pdf_view(request, id,typdoc):
    # ON RECUPERE LES INFOS DU CANDIDAT
    candidat = Candidat.objects.get(id=id)
    document = Document.objects.filter(type__id=typdoc,candidat=candidat,annee=Annee.objects.last()).last()

    context = {
        'candidat':candidat,
        'document':document,
    }
    # TEMPLATE HTML DU PDF
    template_path = '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
    response['Content-Disposition'] = 'filename="DOC-' + str(document.type.libelle).upper() + '-' + str(candidat.nc) + '.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: CANDIDATS AUTORISES
def candidats_autorises_pdf(request, concours,annee):
    typc = TypeConcours.objects.get(id=concours)
    an = Annee.objects.get(id=annee)

    # ON RECUPERE LES CANDIDATURES APPROUVES
    candidatures = Candidature.objects.filter(type_concours=typc,annee=an,status='approuvée')

    context = {
        'candidatures':candidatures,
        'an':an,
        'type_conc':typc,
    }
    # TEMPLATE HTML DU PDF
    template_path = 'pdf/candidats_autorises_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="CANDIDATS AUTORISES - ' + str(typc.code)+' '+str(an.libelle)+ '.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: CANDIDATS AUTORISES
def candidats_declares_admis_pdf(request, concours,annee):
    typc = TypeConcours.objects.get(id=concours)
    an = Annee.objects.get(id=annee)

    # ON RECUPERE LES CANDIDATURES DECLARES ADMIS
    candidatures = Candidature.objects.filter(type_concours=typc,annee=an,decision_finale='admis')

    context = {
        'candidatures':candidatures,
        'an':an,
        'type_conc':typc,
    }
    # TEMPLATE HTML DU PDF
    template_path = 'pdf/candidats_declares_admis_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="CANDIDATS DECLARES ADMIS - ' + str(typc.code)+' '+str(an.libelle)+ '.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: CANDIDATS AUX AUDITIONS
def candidats_oral_pdf(request, concours,annee):
    typc = TypeConcours.objects.get(id=concours)
    an = Annee.objects.get(id=annee)

    # ON RECUPERE LES CANDIDATURES DECLARES ADMIS
    candidatures = Candidature.objects.filter(type_concours=typc,annee=an,decision_finale='en attente',status="approuvée")
    # ON RECUPERE LE SEUIL DE DELIBERATION PROVISOIRE
    deliberarion = get_deliberation_provisoire(typc.id,an.id)

    candidatureList = []
    for candidature in candidatures:
        # ON RECUPERE LA MOYENNE DES EPREUVES ECRITES DU CANDIDAT
        moyenne = get_moyenne_ecrit(candidature.id,an.id)
        if moyenne >= deliberarion:
            candidatureList.append(candidature)


    context = {
        'candidatures':candidatureList,
        'an':an,
        'type_conc':typc,
    }
    # TEMPLATE HTML DU PDF
    template_path = 'pdf/candidats_oral_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="CANDIDATS POUR LES AUDITIONS - ' + str(typc.code)+' '+str(an.libelle)+ '.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: CANDIDATS AUX AUDITIONS
def procedure_preinscription(request):

    context = {}
    # TEMPLATE HTML DU PDF
    template_path = 'pdf/procedure_preinscription.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="PROCEDUDE DE PREINSCRIPTION EN LIGNE.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 recu_paiement_pdf(request, id):
    # ON RECUPERE LES INFOS DU CANDIDAT
    candidat = Candidat.objects.filter(email=request.user.email).last()
    candidature = Candidature.objects.get(id=id)
    paiement = Paiement.objects.filter(candidature=candidature).last()

    context = {
        'candidat':candidat,
        'candidature':candidature,
        'paiement':paiement,
    }
    # TEMPLATE HTML DU PDF
    template_path = 'pdf/recu_paiement_pdf.html'

    # Create a Django response object, and specify content_type as pdf
    response = HttpResponse(content_type='application/pdf')
    # attachment;
    if candidat:
        response['Content-Disposition'] = ' filename="DEMANDE DE PAIEMENT-'+str(candidature.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