"""
Cette Class permet de gerer la personnalisation des
attestations et certificats
"""
import pymongo
from pymongo import MongoClient
import json
from bson import ObjectId
import re
from datetime import datetime
import prj_common as mycommon
import secrets
import inspect
import sys, os
import csv
import pandas as pd
from pymongo import ReturnDocument
import GlobalVariable as MYSY_GV
from math import isnan
import GlobalVariable as MYSY_GV
from datetime import timedelta
from xhtml2pdf import pisa
import jinja2
import ftplib
import pysftp
from flask import send_file


"""
Cette fonction retour la liste des attestions et certificats pour un partenaire
"""
def GetPartnerAttestation_Certificat(diction):
    try:
        """
              Verification de la liste des champs obligatoires
              """
        field_list_obligatoire = ['token',]
        for val in field_list_obligatoire:
            if val not in diction:
                mycommon.myprint(
                    str(inspect.stack()[0][3]) + " -  : La valeur '" + val + "' n'est pas presente dans liste ")
                return False, "Impossible de recuperer la liste des attestations "

        # Recuperation du recid du partner
        mytoken = ""
        if ("token" in diction.keys()):
            if diction['token']:
                mytoken = diction['token']

        partner_recid = mycommon.get_parnter_recid_from_token(mytoken)
        if (partner_recid is False):
            mycommon.myprint(str(inspect.stack()[0][3]) + " Impossible de recuperer la liste des attestations ")
            return False, "Impossible de recuperer la liste des attestations "

        RetObject = []
        for ret_val in MYSY_GV.dbname['attestation_certificat'].find( {"$or":[ {"partner_recid":str(partner_recid), "valide":"1"},
                                                                                              {"partner_recid":'default', "valide":"1"}]}):
            RetObject.append(mycommon.JSONEncoder().encode(ret_val))


        return True, RetObject

    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno))
        return False, "Impossible d'importer les participants  en masse "


"""
Cette fonction prend un nom d'attestation et retourne les informations asociées
 """
def GetSpecificPartnerAttestation_Certificat(diction):
    try:
        """
              Verification de la liste des champs obligatoires
              """
        field_list_obligatoire = ['token', 'nom']
        for val in field_list_obligatoire:
            if val not in diction:
                mycommon.myprint(
                    str(inspect.stack()[0][3]) + " -  : La valeur '" + val + "' n'est pas presente dans liste ")
                return False, "Impossible de recuperer la liste des attestations "

        # Recuperation du recid du partner
        mytoken = ""
        if ("token" in diction.keys()):
            if diction['token']:
                mytoken = diction['token']



        partner_recid = mycommon.get_parnter_recid_from_token(mytoken)
        if (partner_recid is False):
            mycommon.myprint(str(inspect.stack()[0][3]) + " Impossible de recuperer la liste des attestations ")
            return False, "Impossible de recuperer la liste des attestations "

        RetObject = []
        ret_val = MYSY_GV.dbname['attestation_certificat'].find_one({"nom":str(diction['nom']), "valide":"1" })

        if( ret_val is None):
            mycommon.myprint(
                str(inspect.stack()[0][
                        3]) + " Impossible de recuperer les données de ce template ")
            return False, "Impossible de recuperer les données de ce template"


        RetObject.append(mycommon.JSONEncoder().encode(ret_val))


        return True, RetObject

    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno))
        return False, "Impossible de recuperer la liste des attestations "
