"""
Ce fichier permet de gerer les evaluations au sens propre du terme
Par exemple la saisie d'une evaluation planifiée :
- formation,
- ue,
- responsable (rh)
- type eval (proje, td, controle contonie, etc)
- date
- lieu
- ressource
- apprenant
- session_id (la class)

En suite la saisie de la note dans la collection : 'note_evaluation_apprenant'

"""
import ast

import bson
import pymongo
import xlsxwriter
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
import ela_index_bdd_classes as eibdd
import email_mgt as email
import jinja2
from flask import send_file
from xhtml2pdf import pisa
from email.message import EmailMessage
from email.mime.text import MIMEText
from email import encoders
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

"""
Ajout d'une evaluation planifiée
"""
def Add_Evaluation_Planification(diction):
    try:
        diction = mycommon.strip_dictionary(diction)

        """
        Verification des input acceptés
        """
        field_list = ['token', 'code', 'titre', 'description', 'comment',
                      'class_id', 'class_eu_id', 'type_eval_id',
                      'eval_date_heure_debut', 'eval_date_heure_fin', 'statut',  'adress', 'cp', 'ville',
                      'pays', 'responsable_id', 'session_id']

        incom_keys = diction.keys()
        for val in incom_keys:
            if val not in field_list and val.startswith('my_') is False:
                mycommon.myprint(str(
                    inspect.stack()[0][3]) + "  Le champ  '" + val + "' n'est pas autorisé")
                return False, " Les informations fournies sont incorrectes"

        """
        Verification des champs obligatoires
        """
        field_list_obligatoire = ['token', 'code', 'titre',  'class_id', 'class_eu_id', 'type_eval_id',
                                  'eval_date_heure_debut', 'eval_date_heure_fin',]

        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, " Les informations fournies sont incorrectes"

        """
        Verification de l'identité et autorisation de l'entité qui
        appelle cette API
        """
        token = ""
        if ("token" in diction.keys()):
            if diction['token']:
                token = diction['token']

        local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
        if (local_status is not True):
            return local_status, my_partner


        # Verifier que la formation et l'ue de la formation existe et sont valides
        is_existe_class_and_class_ue = MYSY_GV.dbname['myclass'].count_documents({ '_id':ObjectId(str(diction['class_id'])),
                                                                            'list_unite_enseignement._id': str(diction['class_eu_id']),
                                                                            'partner_owner_recid':my_partner['recid'],
                                                                            'valide':'1',
                                                                            'locked':'0'})


        if( is_existe_class_and_class_ue != 1 ):
            mycommon.myprint(
                str(inspect.stack()[0][3]) + " La formation et l'UE ne sont pas cohérents ")
            return False, " La formation et l'UE ne sont pas cohérents "


        """
        Verifier que le type d'évaluation est valide
        """
        is_valide_type_eval = MYSY_GV.dbname['type_evaluation'].count_documents({'_id':ObjectId(str(diction['type_eval_id'])),
                                                                                 'partner_owner_recid': my_partner[
                                                                                     'recid'],
                                                                                 'valide': '1',
                                                                                 'locked': '0'})

        if (is_valide_type_eval != 1):
            mycommon.myprint(
                str(inspect.stack()[0][3]) + " L'identifiant du type d'évaluation est invalide ")
            return False, "  L'identifiant du type d'évaluation est invalide "


        """
        Si responsable_id, alors verifier la validité
        """
        if( 'responsable_id' in diction.keys() and diction['responsable_id']):
            is_valide_responsable = MYSY_GV.dbname['ressource_humaine'].count_documents(
                {'_id': ObjectId(str(diction['responsable_id'])),
                 'partner_recid': my_partner[
                     'recid'],
                 'valide': '1',
                 'locked': '0'})

            if (is_valide_responsable != 1):
                mycommon.myprint(
                    str(inspect.stack()[0][3]) + " L'identifiant du responsable de l'évaluation est invalide ")
                return False, " L'identifiant du responsable de l'évaluation est invalide "


        """
        Si session_id, verifier la validité de la session
        """
        if ('session_id' in diction.keys() and diction['session_id']):
            is_valide_session_id = MYSY_GV.dbname['session_formation'].count_documents(
                {'_id': ObjectId(str(diction['session_id'])),
                 'partner_owner_recid': my_partner[
                     'recid'],
                 'valide': '1',
                })

            if (is_valide_session_id != 1):
                mycommon.myprint(
                    str(inspect.stack()[0][3]) + " L'identifiant de la session (class) est invalide ")
                return False, " L'identifiant de la session (class) est invalide "

        """
        Verifier que les date_heure_debut et date_heure_fin sont ok
        """
        eval_date_heure_debut = str(diction['eval_date_heure_debut']).strip()[0:16]
        local_status = mycommon.CheckisDate_Hours(eval_date_heure_debut)
        if (local_status is False):
            mycommon.myprint(
                str(inspect.stack()[0][
                        3]) + " La date de début d'évaluation n'est pas au format jj/mm/aaaa  hh:mm")

            return False, " La date de début d'évaluation n'est pas au format jj/mm/aaaa  hh:mm"

        eval_date_heure_fin = str(diction['eval_date_heure_fin']).strip()[0:16]
        local_status = mycommon.CheckisDate_Hours(eval_date_heure_fin)
        if (local_status is False):
            mycommon.myprint(
                str(inspect.stack()[0][
                        3]) + " La date de fin d'évaluation n'est pas au format jj/mm/aaaa  hh:mm")

            return False, " La date de fin d'évaluation n'est pas au format jj/mm/aaaa  hh:mm"

        ## Verification de la cohérence des dates. Date_du doit <= Date_au
        if (datetime.strptime(str(eval_date_heure_debut).strip(), '%d/%m/%Y %H:%M') > datetime.strptime(
                str(eval_date_heure_fin).strip(), '%d/%m/%Y %H:%M')):
            mycommon.myprint(
                str(inspect.stack()[0][3]) + " La date debut " + str(eval_date_heure_debut) + " est postérieure à la date de fin " + str(eval_date_heure_fin) + "  ")

            return False, " La date debut " + str(eval_date_heure_debut) + " est postérieure à la date de fin " + str(eval_date_heure_fin) + " "


        new_data = diction
        del diction['token']

        # Initialisation des champs non envoyés à vide
        for val in field_list:
            if val not in diction.keys():
                new_data[str(val)] = ""

        new_data['valide'] = "1"
        new_data['locked'] = "0"

        new_data['date_update'] = str(datetime.now())
        new_data['update_by'] = str(my_partner['_id'])
        new_data['partner_owner_recid'] = str(my_partner['recid'])

        inserted_id = MYSY_GV.dbname['note_evaluation'].insert_one(new_data).inserted_id
        if (not inserted_id):
            mycommon.myprint(
                " Impossible de créer l'évaluation  (2) ")
            return False, "  Impossible de créer l'évaluation  (2)  "


        return True, " L'évaluation a été correctement ajoutée"

    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
        return False, " Impossible de créer l'évaluation "


"""
Mettre à jour une évaluation planifiée
"""
def Update_Evaluation_Planification(diction):
    try:
        diction = mycommon.strip_dictionary(diction)

        """
        Verification des input acceptés
        """
        field_list = ['token', 'evaluation_id', 'code', 'titre', 'description', 'comment',
                      'class_id', 'class_eu_id', 'type_eval_id',
                      'eval_date_heure_debut', 'eval_date_heure_fin', 'statut', 'site_id', 'adress', 'cp', 'ville',
                      'pays', 'responsable_id', 'session_id']

        incom_keys = diction.keys()
        for val in incom_keys:
            if val not in field_list and val.startswith('my_') is False:
                mycommon.myprint(str(
                    inspect.stack()[0][3]) + "  Le champ  '" + val + "' n'est pas autorisé")
                return False, " Les informations fournies sont incorrectes"

        """
        Verification des champs obligatoires
        """
        field_list_obligatoire = ['token', 'evaluation_id', 'code', 'titre',  'class_id', 'class_eu_id', 'type_eval_id',
                                  'eval_date_heure_debut', 'eval_date_heure_fin',]

        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, " Les informations fournies sont incorrectes"

        """
        Verification de l'identité et autorisation de l'entité qui
        appelle cette API
        """
        token = ""
        if ("token" in diction.keys()):
            if diction['token']:
                token = diction['token']

        local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
        if (local_status is not True):
            return local_status, my_partner


        """
        Verifier que class_ue_id est valide
        """
        is_evaluation_id_existe_class = MYSY_GV.dbname['note_evaluation'].count_documents({ '_id':ObjectId(str(diction['evaluation_id'])),
                                                                            'partner_owner_recid':my_partner['recid'],
                                                                                                             'valide': '1',
                                                                                                             'locked': '0'
                                                                                                             })

        if (is_evaluation_id_existe_class != 1):
            mycommon.myprint(
                str(inspect.stack()[0][3]) + " L'identifiant de l'évaluation est invalide  ")
            return False, " L'identifiant de l'évaluation est invalide  "


        # Verifier que la formation et l'ue de la formation existe et sont valides
        is_existe_class_and_class_ue = MYSY_GV.dbname['myclass'].count_documents(
            {'_id': ObjectId(str(diction['class_id'])),
             'list_unite_enseignement._id': str(diction['class_eu_id']),
             'partner_owner_recid': my_partner['recid'],
             'valide': '1',
             'locked': '0'})

        if (is_existe_class_and_class_ue != 1):
            mycommon.myprint(
                str(inspect.stack()[0][3]) + " La formation et l'UE ne sont pas cohérents ")
            return False, " La formation et l'UE ne sont pas cohérents "


        """
        Verifier que le type d'évaluation est valide
        """
        is_valide_type_eval = MYSY_GV.dbname['type_evaluation'].count_documents(
            {'_id': ObjectId(str(diction['type_eval_id'])),
             'partner_owner_recid': my_partner[
                 'recid'],
             'valide': '1',
             'locked': '0'})

        if (is_valide_type_eval != 1):
            mycommon.myprint(
                str(inspect.stack()[0][3]) + " L'identifiant du type d'évaluation est invalide ")
            return False, "  L'identifiant du type d'évaluation est invalide "

        """
                Si responsable_id, alors verifier la validité
                """
        if ('responsable_id' in diction.keys() and diction['responsable_id']):
            is_valide_responsable = MYSY_GV.dbname['ressource_humaine'].count_documents(
                {'_id': ObjectId(str(diction['responsable_id'])),
                 'partner_recid': my_partner[
                     'recid'],
                 'valide': '1',
                 'locked': '0'})

            if (is_valide_responsable != 1):
                mycommon.myprint(
                    str(inspect.stack()[0][3]) + " L'identifiant du responsable de l'évaluation est invalide ")
                return False, " L'identifiant du responsable de l'évaluation est invalide "

        """
        Si session_id, verifier la validité de la session
        """
        if ('session_id' in diction.keys() and diction['session_id']):
            is_valide_session_id = MYSY_GV.dbname['session_formation'].count_documents(
                {'_id': ObjectId(str(diction['session_id'])),
                 'partner_owner_recid': my_partner[
                     'recid'],
                 'valide': '1',
                 })

            if (is_valide_session_id != 1):
                mycommon.myprint(
                    str(inspect.stack()[0][3]) + " L'identifiant de la session (class) est invalide ")
                return False, " L'identifiant de la session (class) est invalide "


        """
        Verifier que les date_heure_debut et date_heure_fin sont ok
        """
        eval_date_heure_debut = str(diction['eval_date_heure_debut']).strip()[0:16]
        local_status = mycommon.CheckisDate_Hours(eval_date_heure_debut)
        if (local_status is False):
            mycommon.myprint(
                str(inspect.stack()[0][
                        3]) + " La date de début d'évaluation n'est pas au format jj/mm/aaaa  hh:mm")

            return False, " La date de début d'évaluation n'est pas au format jj/mm/aaaa  hh:mm"

        eval_date_heure_fin = str(diction['eval_date_heure_fin']).strip()[0:16]
        local_status = mycommon.CheckisDate_Hours(eval_date_heure_fin)
        if (local_status is False):
            mycommon.myprint(
                str(inspect.stack()[0][
                        3]) + " La date de fin d'évaluation n'est pas au format jj/mm/aaaa  hh:mm")

            return False, " La date de fin d'évaluation n'est pas au format jj/mm/aaaa  hh:mm"

        ## Verification de la cohérence des dates. Date_du doit <= Date_au
        if (datetime.strptime(str(eval_date_heure_debut).strip(), '%d/%m/%Y %H:%M') > datetime.strptime(
                str(eval_date_heure_fin).strip(), '%d/%m/%Y %H:%M')):
            mycommon.myprint(
                str(inspect.stack()[0][3]) + " La date debut " + str(
                    eval_date_heure_debut) + " est postérieure à la date de fin " + str(eval_date_heure_fin) + "  ")

            return False, " La date debut " + str(eval_date_heure_debut) + " est postérieure à la date de fin " + str(
                eval_date_heure_fin) + " "


        local_evaluation_id = diction['evaluation_id']
        new_data = diction
        del diction['token']
        del diction['evaluation_id']


        new_data['valide'] = "1"
        new_data['locked'] = "0"

        new_data['date_update'] = str(datetime.now())
        new_data['update_by'] = str(my_partner['_id'])
        new_data['partner_owner_recid'] = str(my_partner['recid'])


        result = MYSY_GV.dbname['note_evaluation'].find_one_and_update(
            {'_id': ObjectId(str(local_evaluation_id)),
             'partner_owner_recid': my_partner['recid'],
             'valide': '1',
             'locked': '0'
             },
            {"$set": new_data},
            upsert=False,
            return_document=ReturnDocument.AFTER
        )



        if (result is None or "_id" not in result.keys()):
            mycommon.myprint(
                " Impossible de mettre à jour l'évaluation (2) ")
            return False, " Impossible de mettre à jour l'évaluation (2)  "




        return True, " L'évaluation a été correctement mise à jour"

    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
        return False, "  Impossible de mettre à jour l'évaluation  "


"""
Recuperation de la liste des evaluation planifiée
"""

def Get_List_Evaluation_Planification_No_Filter(diction):
    try:
        diction = mycommon.strip_dictionary(diction)

        """
        Verification des input acceptés
        """
        field_list = ['token',]

        incom_keys = diction.keys()
        for val in incom_keys:
            if val not in field_list  and val.startswith('my_') is False:
                mycommon.myprint(str(
                    inspect.stack()[0][3]) + "  Le champ  '" + val + "' n'existe pas")
                return False, " Les informations fournies sont incorrectes",

        """
        Verification 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, " Les informations fournies sont incorrectes",

        """
        Verification de l'identité et autorisation de l'entité qui
        appelle cette API
        """
        token = ""
        if ("token" in diction.keys()):
            if diction['token']:
                token = diction['token']

        local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
        if (local_status is not True):
            return local_status, my_partner


        """
                Clés de mise à jour 
                """
        data_cle = {}
        data_cle['partner_owner_recid'] = str(my_partner['recid'])
        data_cle['valide'] = "1"
        data_cle['locked'] = "0"


        RetObject = []
        val_tmp = 0

        for retval in MYSY_GV.dbname['note_evaluation'].find(data_cle).sort([("_id", pymongo.DESCENDING), ]):
            user = retval
            user['id'] = str(val_tmp)
            val_tmp = val_tmp + 1

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

        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) + " - Line : " + str(exc_tb.tb_lineno))
        return False, " Impossible de récupérer la liste des évaluations "


"""
Recuperation de la liste des evaluation planifiée avec des filter sur :
- la formation (code),
- l'UE (code_ue)
- la session (class) (code_session)
"""

def Get_List_Evaluation_Planification_With_Filter(diction):
    try:
        diction = mycommon.strip_dictionary(diction)

        """
        Verification des input acceptés
        """
        field_list = ['token','class_external_code', 'code_session', 'code_ue']

        incom_keys = diction.keys()
        for val in incom_keys:
            if val not in field_list  and val.startswith('my_') is False:
                mycommon.myprint(str(
                    inspect.stack()[0][3]) + "  Le champ  '" + val + "' n'existe pas")
                return False, " Les informations fournies sont incorrectes",

        """
        Verification 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, " Les informations fournies sont incorrectes",

        """
        Verification de l'identité et autorisation de l'entité qui
        appelle cette API
        """
        token = ""
        if ("token" in diction.keys()):
            if diction['token']:
                token = diction['token']

        local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
        if (local_status is not True):
            return local_status, my_partner

        filt_session_id = {}
        list_session_id = []
        if ("code_session" in diction.keys()):
            filt_code_session = {'code_session': {'$regex': str(diction['code_session']), "$options": "i"}}


            qry_list_session_id = {"$and": [{'code_session': {'$regex': str(diction['code_session']), "$options": "i"}},
                                            {'partner_owner_recid': str(my_partner['recid'])}]}

            # print(" ### qry_list_session_id aa = ", qry_list_session_id)
            list_session_id_count = MYSY_GV.dbname['session_formation'].count_documents(qry_list_session_id)

            if (list_session_id_count <= 0):
                # Aucune session
                return True, []

            for val in MYSY_GV.dbname['session_formation'].find(qry_list_session_id):
                list_session_id.append(str(val['_id']))

            #print(" ### liste des Id des sessions eligible list_session_id = ", list_session_id)
            filt_session_id = {'session_id': {'$in': list_session_id, }}



        filt_class_id = {}
        list_class_id = []
        if ("class_external_code" in diction.keys()):
            filt_class_title = {'external_code': {'$regex': str(diction['class_external_code']), "$options": "i"}}


            qry_list_class_id = {"$and": [{'external_code': {'$regex': str(diction['class_external_code']), "$options": "i"}},
                                            {'partner_owner_recid': str(my_partner['recid'])}]}

            print(" ### qry_list_class_id aa = ", qry_list_class_id)
            list_class_id_count = MYSY_GV.dbname['myclass'].count_documents(qry_list_class_id)

            if (list_class_id_count <= 0):
                # Aucune session
                return True, []

            for val in MYSY_GV.dbname['myclass'].find(qry_list_class_id):
                list_class_id.append(str(val['_id']))

            # print(" ### liste des Id des sessions eligible list_session_id = ", list_session_id)
            filt_class_id = {'class_id': {'$in': list_class_id, }}



        filt_ue_id = {}
        list_ue_id = []
        if ("code_ue" in diction.keys()):
            filt_code_ue = {'code': {'$regex': str(diction['code_ue']), "$options": "i"}}

            """qry_list_session_id = { { '$and' :[ {'code_session': {'$regex': str(diction['code_session']), "$options": "i"}},
                                                {'partner_owner_recid': str(partner_recid)} ]}, {'_id':1}}
            """

            qry_list_ue_id = {"$and": [{'code': {'$regex': str(diction['code_ue']), "$options": "i"}},
                                            {'partner_owner_recid': str(my_partner['recid'])}]}

            #print(" ### qry_list_session_id aa = ", qry_list_ue_id)
            list_ue_id_count = MYSY_GV.dbname['unite_enseignement'].count_documents(qry_list_ue_id)

            if (list_ue_id_count <= 0):
                # Aucune session
                return True, []

            for val in MYSY_GV.dbname['unite_enseignement'].find(qry_list_ue_id):
                list_ue_id.append(str(val['_id']))


            filt_ue_id = {'class_eu_id': {'$in': list_ue_id, }}
            #print(" ### filt_ue_id des Id list_ue_id ", filt_ue_id)


        """
                Clés de mise à jour 
                """
        data_cle = {}
        data_cle['partner_owner_recid'] = str(my_partner['recid'])
        data_cle['valide'] = "1"
        data_cle['locked'] = "0"

        query = {"$and": [filt_session_id, filt_class_id, filt_ue_id, data_cle]}



        RetObject = []
        val_tmp = 0

        for retval in MYSY_GV.dbname['note_evaluation'].find(query).sort([("_id", pymongo.DESCENDING), ]):
            user = retval
            user['id'] = str(val_tmp)
            val_tmp = val_tmp + 1

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

        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) + " - Line : " + str(exc_tb.tb_lineno))
        return False, " Impossible de récupérer la liste des évaluations "



"""
Recuperer les données d'une évaluation planifiée
"""
def Get_Given_Evaluation_Planification(diction):
    try:
        diction = mycommon.strip_dictionary(diction)

        """
        Verification des input acceptés
        """
        field_list = ['token', 'evaluation_id']

        incom_keys = diction.keys()
        for val in incom_keys:
            if val not in field_list  and val.startswith('my_') is False:
                mycommon.myprint(str(
                    inspect.stack()[0][3]) + "  Le champ  '" + val + "' n'existe pas")
                return False, " Les informations fournies sont incorrectes",

        """
        Verification des champs obligatoires
        """
        field_list_obligatoire = ['token', 'evaluation_id' ]
        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, " Les informations fournies sont incorrectes",

        """
        Verification de l'identité et autorisation de l'entité qui
        appelle cette API
        """
        token = ""
        if ("token" in diction.keys()):
            if diction['token']:
                token = diction['token']

        local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
        if (local_status is not True):
            return local_status, my_partner

        """
                Clés de mise à jour 
                """
        data_cle = {}
        data_cle['partner_owner_recid'] = str(my_partner['recid'])
        data_cle['valide'] = "1"
        data_cle['locked'] = "0"
        data_cle['_id'] = ObjectId(str(diction['evaluation_id']))


        RetObject = []
        val_tmp = 0

        for retval in MYSY_GV.dbname['note_evaluation'].find(data_cle):
            user = retval
            user['id'] = str(val_tmp)
            val_tmp = val_tmp + 1

            # Recuperer l'internal url de la formation
            class_data = MYSY_GV.dbname['myclass'].find_one({'_id':ObjectId(str(retval['class_id'])),
                                                             'partner_owner_recid':str(my_partner['recid'])})

            user['class_internal_url'] = str(class_data['internal_url'])

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

        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) + " - Line : " + str(exc_tb.tb_lineno))
        return False, " Impossible de récupérer le types d'évaluation  "



"""
Supprimer une evaluation planifiée

Regle :
Un évaluation n'est supprimable que s'il n'y pas d'incrit dans la collection "note_evaluation_participant"
"""
def Delete_Evaluation_Planification(diction):
    try:
        diction = mycommon.strip_dictionary(diction)

        """
        Verification des input acceptés
        """
        field_list = ['token',  'evaluation_id']

        incom_keys = diction.keys()
        for val in incom_keys:
            if val not in field_list and val.startswith('my_') is False:
                mycommon.myprint(str(
                    inspect.stack()[0][3]) + "  Le champ  '" + val + "' n'est pas autorisé")
                return False, " Les informations fournies sont incorrectes"

        """
        Verification des champs obligatoires
        """
        field_list_obligatoire = ['token', 'evaluation_id' ]

        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, " Les informations fournies sont incorrectes"

        """
        Verification de l'identité et autorisation de l'entité qui
        appelle cette API
        """
        token = ""
        if ("token" in diction.keys()):
            if diction['token']:
                token = diction['token']

        local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
        if (local_status is not True):
            return local_status, my_partner


        """
        Verifier que class_ue_id est valide
        """
        is_evaluation_id_existe_class = MYSY_GV.dbname['note_evaluation'].count_documents({ '_id':ObjectId(str(diction['evaluation_id'])),
                                                                            'partner_owner_recid':my_partner['recid'],
                                                                                                             'valide': '1',
                                                                                                             'locked': '0'
                                                                                                             })

        if (is_evaluation_id_existe_class != 1):
            mycommon.myprint(
                str(inspect.stack()[0][3]) + " L'identifiant de l'évaluation est invalide  ")
            return False, " L'identifiant de l'évaluation est invalide  "

        note_evaluation_participant_count = MYSY_GV.dbname['note_evaluation_participant'].count_documents({'evaluation_id':str(diction['evaluation_id']),
                                                                                                          'partner_owner_recid':str(my_partner['recid']),
                                                                                                           'valide':'1'})

        if( note_evaluation_participant_count > 0 ):
            mycommon.myprint(
                str(inspect.stack()[0][3]) + " Il y a "+str(note_evaluation_participant_count)+" inscription(s) pour cette evaluation. Suppression annulée  ")
            return False, "  Il y a "+str(note_evaluation_participant_count)+" inscription(s) pour cette evaluation. Suppression annulée  "


        delete = MYSY_GV.dbname['note_evaluation'].delete_one({ '_id':ObjectId(str(diction['evaluation_id'])),
                                                                            'partner_owner_recid':my_partner['recid'],
                                                                                                             'valide': '1',
                                                                                                             'locked': '0'
                                                                                                             } )



        return True, " La évaluation a été correctement supprimée"



    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
        return False, "  Impossible de supprimer l'évaluation  "

"""
Inscrire des participants ou groupe de participants a un évaluation
"""

def Record_Participant_To_Evaluation(diction):
    try:
        diction = mycommon.strip_dictionary(diction)

        """
        Verification des input acceptés
        """
        field_list = ['token', 'evaluation_id', 'tab_inscription_id', 'tab_group_inscription_id']

        incom_keys = diction.keys()
        for val in incom_keys:
            if val not in field_list and val.startswith('my_') is False:
                mycommon.myprint(str(
                    inspect.stack()[0][3]) + "  Le champ  '" + val + "' n'est pas autorisé")
                return False, " Les informations fournies sont incorrectes"

        """
        Verification des champs obligatoires
        """
        field_list_obligatoire = ['token', 'evaluation_id', 'tab_inscription_id', 'tab_group_inscription_id']

        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, " Les informations fournies sont incorrectes"

        """
        Verification de l'identité et autorisation de l'entité qui
        appelle cette API
        """
        token = ""
        if ("token" in diction.keys()):
            if diction['token']:
                token = diction['token']

        local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
        if (local_status is not True):
            return local_status, my_partner


        """
        Verifier que l'evaluation est valide
        """
        is_evaluation_valide = MYSY_GV.dbname['note_evaluation'].count_documents({"_id":ObjectId(str(diction['evaluation_id'])),
                                                                                  'valide':'1',
                                                                                  'locked':'0',
                                                                                  'partner_owner_recid':str(my_partner['recid'])})

        if( is_evaluation_valide != 1):
            mycommon.myprint(
                str(inspect.stack()[0][3]) + " L'identifiant de l'évaluation n'est pas valide  ")
            return False, " L'identifiant de l'évaluation n'est pas valide "

        tab_inscription_id = str(diction['tab_inscription_id']).split(",")
        for inscription_id in tab_inscription_id:
            # Verifier que le stagiaire est bien inscrit. Le statut de l'inscription doit etre "1"
            if( inscription_id ):
                is_inscription_valide = MYSY_GV.dbname['inscription'].count_documents(
                    {'_id': ObjectId(str(inscription_id)),
                     'status': '1',
                     'partner_owner_recid': str(my_partner['recid'])})

                if (is_inscription_valide != 1):
                    mycommon.myprint(
                        str(inspect.stack()[0][
                                3]) + "  L'identifiant de l'inscription "+str(inscription_id)+" est invalide ")
                    return False, "  L'identifiant de l'inscription  "+str(inscription_id)+" est invalide "



        tab_group_inscription_id = str(diction['tab_group_inscription_id']).split(",")


        for group_inscription_id in tab_group_inscription_id:
            # Verifier que le stagiaire est bien inscrit. Le statut de l'inscription doit etre "1"
            if( group_inscription_id ):
                is_tab_inscription_valide = MYSY_GV.dbname['group_inscription'].count_documents(
                    {'_id': ObjectId(str(group_inscription_id)),
                     'status': '1',
                     'partner_owner_recid': str(my_partner['recid'])})

                if (is_tab_inscription_valide != 1):
                    mycommon.myprint(
                        str(inspect.stack()[0][
                                3]) + "  L'identifiant du group d'inscription " + str(group_inscription_id) + " est invalide ")
                    return False, "  L'identifiant du group d'inscription " + str(group_inscription_id) + " est invalide "



        """
        Gestion des inscription des inscrits (PAS LES GROUPE. Ils seront traités plus bas)
        """
        warning_msg = ""
        is_warning = ""
        for inscription_id in tab_inscription_id:
            if( inscription_id ):
                new_data = {}
                new_data['evaluation_id'] = str(diction['evaluation_id'])
                new_data['inscription_id'] = str(inscription_id)
                new_data['group_inscription_id'] = ""
                new_data['note'] = ""
                new_data['valide'] = "1"
                new_data['locked'] = "0"
                new_data['partner_owner_recid'] = str(my_partner['recid'])
                new_data['date_update'] = str(datetime.now())
                new_data['update_by'] = str(my_partner['_id'])

                ret_val = MYSY_GV.dbname['note_evaluation_participant'].find_one_and_update(
                    {'evaluation_id': str(diction['evaluation_id']), 'inscription_id': str(inscription_id),
                     'partner_owner_recid':str(my_partner['recid'])},
                    {"$set": new_data},
                    return_document=ReturnDocument.AFTER,
                    upsert=True,
                )

                if (ret_val is None):
                    mycommon.myprint(str(inspect.stack()[0][3]) + " WARNING : Impossible d'inscrire la participant : " + str(inscription_id))
                    is_warning = "1"
                    warning_msg = warning_msg + "\n Impossible d'inscrire la participant " + str(inscription_id)

        #warning_msg = ""
        #is_warning = ""
        for group_inscription_id in tab_group_inscription_id:
            if( group_inscription_id ):
                new_data = {}
                new_data['evaluation_id'] = str(diction['evaluation_id'])
                new_data['inscription_id'] = ""
                new_data['group_inscription_id'] = str(group_inscription_id)
                new_data['note'] = ""
                new_data['valide'] = "1"
                new_data['locked'] = "0"
                new_data['date_update'] = str(datetime.now())
                new_data['update_by'] = str(my_partner['_id'])
                new_data['partner_owner_recid'] = str(my_partner['recid'])

                ret_val = MYSY_GV.dbname['note_evaluation_participant'].find_one_and_update(
                    {'evaluation_id': str(diction['evaluation_id']), 'group_inscription_id': str(group_inscription_id),
                     'partner_owner_recid':str(my_partner['recid'])},
                    {"$set": new_data},
                    return_document=ReturnDocument.AFTER,
                    upsert=True,
                )

                if (ret_val is None):
                    mycommon.myprint(str(
                        inspect.stack()[0][3]) + " WARNING : Impossible d'inscrire le groupe " + str(group_inscription_id))
                    is_warning = "1"
                    warning_msg = warning_msg + "\n Impossible d'inscrire le groupe " + str(group_inscription_id)


        if (is_warning == "1"):
            return True, str(warning_msg)

        return True, " L'inscription a été correctement faite"

    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
        return False, "Impossible d'inscrire les participants à l'évaluation "


"""
Supprimer / Desinscrire des participants ou groupes de participants
a un évaluation
"""
def Delete_Participant_From_Evaluation(diction):
    try:
        diction = mycommon.strip_dictionary(diction)

        """
        Verification des input acceptés
        """
        field_list = ['token', 'evaluation_id', 'tab_inscription_id',]

        incom_keys = diction.keys()
        for val in incom_keys:
            if val not in field_list and val.startswith('my_') is False:
                mycommon.myprint(str(
                    inspect.stack()[0][3]) + "  Le champ  '" + val + "' n'est pas autorisé")
                return False, " Les informations fournies sont incorrectes"

        """
        Verification des champs obligatoires
        """
        field_list_obligatoire = ['token', 'evaluation_id', 'tab_inscription_id', ]

        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, " Les informations fournies sont incorrectes"

        """
        Verification de l'identité et autorisation de l'entité qui
        appelle cette API
        """
        token = ""
        if ("token" in diction.keys()):
            if diction['token']:
                token = diction['token']

        local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
        if (local_status is not True):
            return local_status, my_partner

        """
        Verifier que l'evaluation est valide
        """
        is_evaluation_valide = MYSY_GV.dbname['note_evaluation'].count_documents(
            {"_id": ObjectId(str(diction['evaluation_id'])),
             'valide': '1',
             'locked': '0',
             'partner_owner_recid': str(my_partner['recid'])})

        if (is_evaluation_valide != 1):
            mycommon.myprint(
                str(inspect.stack()[0][3]) + " L'identifiant de l'évaluation n'est pas valide  ")
            return False, " L'identifiant de l'évaluation n'est pas valide "

        tab_id_to_delete = []

        tab_inscription_id = str(diction['tab_inscription_id']).split(",")
        for inscription_id in tab_inscription_id:
            if( inscription_id ):
                # Verifier que le stagiaire est bien inscrit. Le statut de l'inscription doit etre "1"

                is_inscription_valide = MYSY_GV.dbname['note_evaluation_participant'].count_documents(
                    {'_id': ObjectId(str(inscription_id)),
                     'partner_owner_recid': str(my_partner['recid'])})

                if (is_inscription_valide != 1):
                    mycommon.myprint(
                        str(inspect.stack()[0][
                                3]) + "  L'identifiant de l'inscription " + str(inscription_id) + " est invalide ")
                    return False, "  L'identifiant de l'inscription  " + str(inscription_id) + " est invalide "

                tab_id_to_delete.append(ObjectId(str(inscription_id)))


        warning_msg = ""
        is_warning = ""

        # Suppression des inscription
        if( len(tab_id_to_delete) > 0 and tab_id_to_delete[0]):
            qry_delete_inscription = {'partner_owner_recid': str(my_partner['recid']),
                                  "_id": {"$in": tab_id_to_delete},
                                  }

            print(" ### qry_delete_inscription = ", qry_delete_inscription )

            MYSY_GV.dbname['note_evaluation_participant'].delete_many(qry_delete_inscription)



        return True, " La suppression a été correctement faite"

    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
        return False, "Impossible de supprimer les inscriptions à l'évaluation "


"""
Mise à jour note evaluation
Cette fonction met à jour la note d'un inscrit ou groupe d'inscrit.
{note_evaluation_participant_id:'kjdskjkdj',
tab_participant_note [
    {note_evaluation_participant_id:'4444', note:'33'},
    {note_evaluation_participant_id:'4444', note:'33'}
    ]
}
"""

def Update_Participant_Evaluation_Note(diction):
    try:
        diction = mycommon.strip_dictionary(diction)

        """
        Verification des input acceptés
        """
        field_list = ['token', 'evaluation_id', 'tab_participant_note']

        incom_keys = diction.keys()
        for val in incom_keys:
            if val not in field_list and val.startswith('my_') is False:
                mycommon.myprint(str(
                    inspect.stack()[0][3]) + "  Le champ  '" + val + "' n'est pas autorisé")
                return False, " Les informations fournies sont incorrectes"

        """
        Verification des champs obligatoires
        """
        field_list_obligatoire = ['token', 'evaluation_id', 'tab_participant_note']

        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, " Les informations fournies sont incorrectes"

        """
        Verification de l'identité et autorisation de l'entité qui
        appelle cette API
        """
        token = ""
        if ("token" in diction.keys()):
            if diction['token']:
                token = diction['token']

        local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
        if (local_status is not True):
            return local_status, my_partner

        """
        Verifier que l'evaluation est valide
        """
        is_evaluation_valide = MYSY_GV.dbname['note_evaluation'].count_documents(
            {"_id": ObjectId(str(diction['evaluation_id'])),
             'valide': '1',
             'locked': '0',
             'partner_owner_recid': str(my_partner['recid'])})

        if (is_evaluation_valide != 1):
            mycommon.myprint(
                str(inspect.stack()[0][3]) + " L'identifiant de l'évaluation n'est pas valide  ")
            return False, " L'identifiant de l'évaluation n'est pas valide "

        JSON_tab_participant_note = ast.literal_eval(diction['tab_participant_note'])

        for val in JSON_tab_participant_note:
            if( '_id' in val.keys() and val['_id'] ):
                #print(" #### VAL = ", val)
                new_data = {}
                if("note" in  val.keys() ):
                    new_data['note'] = str(val['note'])
                else:
                    new_data['note'] = "-1"

                new_data['valide'] = "1"
                new_data['locked'] = "0"
                new_data['date_update'] = str(datetime.now())
                new_data['update_by'] = str(my_partner['_id'])
                new_data['partner_owner_recid'] = str(my_partner['recid'])

                ret_val = MYSY_GV.dbname['note_evaluation_participant'].find_one_and_update(
                    {'_id': ObjectId(str(val['_id'])),
                     'partner_owner_recid': str(my_partner['recid'])},
                    {"$set": new_data},
                    return_document=ReturnDocument.AFTER,
                    upsert=False,
                )


        return True, " La mise à jour des notes été correctement faite"

    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
        return False, "Impossible de mettre à jour les notes "


"""
Recuperer la liste des inscrits et groupe inscrit à une 
evaluation
"""

def Get_List_Participant_To_Evaluation(diction):
    try:
        diction = mycommon.strip_dictionary(diction)

        """
        Verification des input acceptés
        """
        field_list = ['token', 'evaluation_id', ]

        incom_keys = diction.keys()
        for val in incom_keys:
            if val not in field_list and val.startswith('my_') is False:
                mycommon.myprint(str(
                    inspect.stack()[0][3]) + "  Le champ  '" + val + "' n'est pas autorisé")
                return False, " Les informations fournies sont incorrectes"

        """
        Verification des champs obligatoires
        """
        field_list_obligatoire = ['token', 'evaluation_id', ]

        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, " Les informations fournies sont incorrectes"

        """
        Verification de l'identité et autorisation de l'entité qui
        appelle cette API
        """
        token = ""
        if ("token" in diction.keys()):
            if diction['token']:
                token = diction['token']

        local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
        if (local_status is not True):
            return local_status, my_partner


        """
        Verifier que l'evaluation est valide
        """
        is_evaluation_valide = MYSY_GV.dbname['note_evaluation'].count_documents({"_id":ObjectId(str(diction['evaluation_id'])),
                                                                                  'valide':'1',
                                                                                  'locked':'0',
                                                                                  'partner_owner_recid':str(my_partner['recid'])})

        if( is_evaluation_valide != 1):
            mycommon.myprint(
                str(inspect.stack()[0][3]) + " L'identifiant de l'évaluation n'est pas valide  ")
            return False, " L'identifiant de l'évaluation n'est pas valide "

        RetObject = []
        nb_val = 0

        for retval in MYSY_GV.dbname['note_evaluation_participant'].find({'evaluation_id':str(diction['evaluation_id']),
                                                                          'valide':'1',
                                                                          'locked':'0',
                                                                          'partner_owner_recid':str(my_partner['recid']),
                                                                          }):
            user = retval
            nom_apprenant = ""
            prenom_apprenant = ""
            email_apprenant = ""
            groupe = ""
            if( "inscription_id" in retval and retval['inscription_id']):
                # Recuprer les données de l'inscrit
                inscription_data = MYSY_GV.dbname['inscription'].find_one({'_id':ObjectId(str(retval['inscription_id']))},
                                                                        {'_id':1, 'apprenant_id':1})

                apprenant_data = MYSY_GV.dbname['apprenant'].find_one({'_id':ObjectId(str(inscription_data['apprenant_id']))},
                                                                        {'_id':1, 'nom':1, 'prenom':1, 'email':1})


                nom_apprenant = apprenant_data['nom']
                prenom_apprenant = apprenant_data['prenom']
                email_apprenant = apprenant_data['email']

            user['nom'] = nom_apprenant
            user['prenom'] = prenom_apprenant
            user['email'] = email_apprenant
            user['id'] = str(nb_val)
            if( "note" not in retval.keys() ):
                user['note'] = "-1"

            nb_val = nb_val + 1

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

        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 récupérer la liste des inscrits à l'évaluation"


"""
Recuperation des notes d'un inscrit a une liste de session_id
"""
def Get_List_Participant_Notes(diction):
    try:
        diction = mycommon.strip_dictionary(diction)

        """
        Verification des input acceptés
        """
        field_list = ['token', 'tab_session_id', 'tab_inscription_id']

        incom_keys = diction.keys()
        for val in incom_keys:
            if val not in field_list and val.startswith('my_') is False:
                mycommon.myprint(str(
                    inspect.stack()[0][3]) + "  Le champ  '" + val + "' n'est pas autorisé")
                return False, " Les informations fournies sont incorrectes"

        """
        Verification des champs obligatoires
        """
        field_list_obligatoire = ['token', 'tab_session_id', 'tab_inscription_id']

        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, " Les informations fournies sont incorrectes"

        """
        Verification de l'identité et autorisation de l'entité qui
        appelle cette API
        """
        token = ""
        if ("token" in diction.keys()):
            if diction['token']:
                token = diction['token']

        local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
        if (local_status is not True):
            return local_status, my_partner

        tab_session_id = ""
        if ("tab_session_id" in diction.keys()):
            if diction['tab_session_id']:
                tab_session_id = diction['tab_session_id']

        tab_inscription_id = ""
        if ("tab_inscription_id" in diction.keys()):
            if diction['tab_inscription_id']:
                tab_inscription_id = diction['tab_inscription_id']

        tab_my_session_ids = str(tab_session_id).split(",")
        tab_my_inscription_ids = str(tab_inscription_id).split(",")

        """
        Verification de la validité de la liste des inscription
        """


        #print("tab_my_session_ids = ", tab_my_session_ids)


        for my_inscription_id in tab_my_inscription_ids:
            # Verifier qui la formation n'a pas deja été evaluée



            tmp_count = MYSY_GV.dbname['inscription'].count_documents({'session_id': {'$in': tab_my_session_ids, },
                                                                       '_id': ObjectId(str(my_inscription_id)),
                                                                       'partner_owner_recid': str(my_partner['recid']),
                                                                       } )

            if (tmp_count != 1):
                mycommon.myprint(str(inspect.stack()[0][3]) + " L'inscription "+str(my_inscription_id)+" est invalide ")
                return False, " L'inscription "+str(my_inscription_id)+" est invalide "

        """
        Verification de la validité de la liste des sessions
        """
        for my_session_ids in tab_my_session_ids:
            # Verifier qui la formation n'a pas deja été evaluée
            tmp_count = MYSY_GV.dbname['session_formation'].count_documents({'_id': ObjectId(str(my_session_ids)),
                                                                             'partner_owner_recid': str(my_partner['recid']),
                                                                             'valide':'1'
                                                                                       } )

            if (tmp_count != 1):
                mycommon.myprint(str(inspect.stack()[0][3]) + " La session "+str(my_session_ids)+" est invalide ")
                return False, " L'inscription "+str(my_session_ids)+" est invalide "


        RetObject = []
        nb_val = 0

        query = [{'$match': {'inscription_id': {'$in':tab_my_inscription_ids}, 'partner_owner_recid': str(my_partner['recid']),
                              }},
                 {'$sort': {'_id': -1}},
                 {'$lookup':
                     {
                         'from': 'note_evaluation',
                         "let": {'evaluation_id': "$evaluation_id", 'partner_owner_recid': '$partner_owner_recid'},
                         'pipeline': [{'$match':
                             {'$expr': {'$and': [
                                 {'$eq': ["$valide", "1"]},
                                 {'$eq': ["$_id", {'$convert': {
                                     'input': "$$evaluation_id",
                                     'to': "objectId",
                                     'onError': {'error': 'true'},
                                     'onNull': {'isnull': 'true'}
                                 }}]},

                             ]}}},
                         ], 'as': 'note_evaluation_collection'}
                 }

                 ]
        print("#### Get_List_Participant_Notes laa 01 : query = ", query)
        for retval in MYSY_GV.dbname['note_evaluation_participant'].aggregate(query):
            if( "note_evaluation_collection" in retval.keys() ):
                user = {}
                nom_apprenant = ""
                prenom_apprenant = ""
                email_apprenant = ""
                groupe = ""
                if( "inscription_id" in retval and retval['inscription_id']):
                    # Recuprer les données de l'inscrit
                    inscription_data = MYSY_GV.dbname['inscription'].find_one({'_id':ObjectId(str(retval['inscription_id']))},
                                                                            {'_id':1, 'apprenant_id':1})

                    apprenant_data = MYSY_GV.dbname['apprenant'].find_one({'_id':ObjectId(str(inscription_data['apprenant_id']))},
                                                                            {'_id':1, 'nom':1, 'prenom':1, 'email':1})


                    nom_apprenant = apprenant_data['nom']
                    prenom_apprenant = apprenant_data['prenom']
                    email_apprenant = apprenant_data['email']

                user['_id'] = str(retval['_id'])
                user['evaluation_id'] = str(retval['evaluation_id'])
                user['inscription_id'] = str(retval['inscription_id'])
                user['note'] = str(retval['note'])

                user['note_evaluation_id'] = str(retval['note_evaluation_collection'][0]['_id'])
                user['note_evaluation_code'] = str(retval['note_evaluation_collection'][0]['code'])

                user['note_evaluation_titre'] = str(retval['note_evaluation_collection'][0]['titre'])
                user['session_id'] = str(retval['note_evaluation_collection'][0]['session_id'])
                user['class_eu_id'] = str(retval['note_evaluation_collection'][0]['class_eu_id'])

                class_ue_code = ""
                class_ue_titre = ""
                ue_data = MYSY_GV.dbname['unite_enseignement'].find_one({'_id':ObjectId(str(user['class_eu_id'])),
                                                                          'valide':'1',
                                                                          'locked':'0',
                                                                          'partner_owner_recid':str(my_partner['recid'])})
                if( "code" in ue_data.keys() ):
                    class_ue_code = str(ue_data['code'])
                if ("titre" in ue_data.keys()):
                    class_ue_titre = str(ue_data['titre'])

                user['class_ue_code'] = class_ue_code
                user['class_ue_titre'] = class_ue_titre


                user['type_eval_id'] = str(retval['note_evaluation_collection'][0]['type_eval_id'])
                type_eval_data = MYSY_GV.dbname['type_eval_id'].find_one({'_id':ObjectId(str(user['type_eval_id'])),
                                                                          'valide':'1',
                                                                          'locked':'0',
                                                                          'partner_owner_recid':str(my_partner['recid'])})
                if( type_eval_data and 'code' in type_eval_data.keys() ):
                    user['type_eval_code'] = type_eval_data['code']
                else:
                    user['type_eval_code'] = ""




                user['eval_date_heure_debut'] = str(retval['note_evaluation_collection'][0]['eval_date_heure_debut'])
                user['eval_date_heure_fin'] = str(retval['note_evaluation_collection'][0]['eval_date_heure_fin'])





                user['nom'] = nom_apprenant
                user['prenom'] = prenom_apprenant
                user['email'] = email_apprenant
                user['id'] = str(nb_val)
                if( "note" not in retval.keys() ):
                    user['note'] = "-1"

                nb_val = nb_val + 1

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

        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 récupérer les notes de l'apprenant"


"""
Exporter les notes de l'apprenant dans un doc excel
"""
def Export_Excel_List_Participant_Notes(diction):
    try:
        diction = mycommon.strip_dictionary(diction)

        """
        Verification des input acceptés
        """
        field_list = ['token', 'tab_session_id', 'tab_inscription_id']

        incom_keys = diction.keys()
        for val in incom_keys:
            if val not in field_list and val.startswith('my_') is False:
                mycommon.myprint(str(
                    inspect.stack()[0][3]) + "  Le champ  '" + val + "' n'est pas autorisé")
                return False, " Les informations fournies sont incorrectes"

        """
        Verification des champs obligatoires
        """
        field_list_obligatoire = ['token', 'tab_session_id', 'tab_inscription_id']

        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, " Les informations fournies sont incorrectes"

        """
        Verification de l'identité et autorisation de l'entité qui
        appelle cette API
        """
        token = ""
        if ("token" in diction.keys()):
            if diction['token']:
                token = diction['token']

        local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
        if (local_status is not True):
            return local_status, my_partner

        tab_session_id = ""
        if ("tab_session_id" in diction.keys()):
            if diction['tab_session_id']:
                tab_session_id = diction['tab_session_id']

        tab_inscription_id = ""
        if ("tab_inscription_id" in diction.keys()):
            if diction['tab_inscription_id']:
                tab_inscription_id = diction['tab_inscription_id']

        tab_my_session_ids = str(tab_session_id).split(",")
        tab_my_inscription_ids = str(tab_inscription_id).split(",")

        """
        Verification de la validité de la liste des inscription
        """


        #print("tab_my_session_ids = ", tab_my_session_ids)


        for my_inscription_id in tab_my_inscription_ids:
            # Verifier qui la formation n'a pas deja été evaluée



            tmp_count = MYSY_GV.dbname['inscription'].count_documents({'session_id': {'$in': tab_my_session_ids, },
                                                                       '_id': ObjectId(str(my_inscription_id)),
                                                                       'partner_owner_recid': str(my_partner['recid']),
                                                                       } )

            if (tmp_count != 1):
                mycommon.myprint(str(inspect.stack()[0][3]) + " L'inscription "+str(my_inscription_id)+" est invalide ")
                return False, " L'inscription "+str(my_inscription_id)+" est invalide "

        """
        Verification de la validité de la liste des sessions
        """
        for my_session_ids in tab_my_session_ids:
            # Verifier qui la formation n'a pas deja été evaluée
            tmp_count = MYSY_GV.dbname['session_formation'].count_documents({'_id': ObjectId(str(my_session_ids)),
                                                                             'partner_owner_recid': str(my_partner['recid']),
                                                                             'valide':'1'
                                                                                       } )

            if (tmp_count != 1):
                mycommon.myprint(str(inspect.stack()[0][3]) + " La session "+str(my_session_ids)+" est invalide ")
                return False, " L'inscription "+str(my_session_ids)+" est invalide "


        RetObject = []
        nb_val = 0

        query = [{'$match': {'inscription_id': {'$in':tab_my_inscription_ids}, 'partner_owner_recid': str(my_partner['recid']),
                              }},
                 {'$sort': {'_id': -1}},
                 {'$lookup':
                     {
                         'from': 'note_evaluation',
                         "let": {'evaluation_id': "$evaluation_id", 'partner_owner_recid': '$partner_owner_recid'},
                         'pipeline': [{'$match':
                             {'$expr': {'$and': [
                                 {'$eq': ["$valide", "1"]},
                                 {'$eq': ["$_id", {'$convert': {
                                     'input': "$$evaluation_id",
                                     'to': "objectId",
                                     'onError': {'error': 'true'},
                                     'onNull': {'isnull': 'true'}
                                 }}]},

                             ]}}},
                         ], 'as': 'note_evaluation_collection'}
                 }

                 ]
        print("#### Export_Excel_List_Participant_Notes : query = ", query)

        ts = datetime.now().timestamp()
        ts = str(ts).replace(".", "").replace(",", "")[-5:]

        orig_file_name = "Export_Notes_" + str(ts) + ".xlsx"
        outputFilename = str(MYSY_GV.TEMPORARY_DIRECTORY) + "/" + str(orig_file_name)

        tab_exported_fields_header = ["Formation", "Classe",  "Nom", "Prenom", "Email", "UE Code", "UE Titre",
                                      "Evaluation", "Début Evaluation", "Fin Evaluation", "Note"
                                     ]

        # Create a workbook and add a worksheet.
        workbook = xlsxwriter.Workbook(outputFilename)
        worksheet = workbook.add_worksheet()

        row = 0
        column = 0
        """
               Creation de l'entete du fichier excel
               """

        for header_item in tab_exported_fields_header:
            worksheet.write(row, column, header_item)
            column += 1


        for retval in MYSY_GV.dbname['note_evaluation_participant'].aggregate(query):
            if( "note_evaluation_collection" in retval.keys() ):
                user = {}
                nom_apprenant = ""
                prenom_apprenant = ""
                email_apprenant = ""
                groupe = ""
                if( "inscription_id" in retval and retval['inscription_id']):
                    # Recuprer les données de l'inscrit
                    inscription_data = MYSY_GV.dbname['inscription'].find_one({'_id':ObjectId(str(retval['inscription_id']))},
                                                                            {'_id':1, 'apprenant_id':1})

                    apprenant_data = MYSY_GV.dbname['apprenant'].find_one({'_id':ObjectId(str(inscription_data['apprenant_id']))},
                                                                            {'_id':1, 'nom':1, 'prenom':1, 'email':1})


                    nom_apprenant = apprenant_data['nom']
                    prenom_apprenant = apprenant_data['prenom']
                    email_apprenant = apprenant_data['email']

                user['_id'] = str(retval['_id'])
                user['evaluation_id'] = str(retval['evaluation_id'])
                user['inscription_id'] = str(retval['inscription_id'])
                user['note'] = str(retval['note'])

                user['note_evaluation_id'] = str(retval['note_evaluation_collection'][0]['_id'])
                user['note_evaluation_code'] = str(retval['note_evaluation_collection'][0]['code'])

                user['note_evaluation_titre'] = str(retval['note_evaluation_collection'][0]['titre'])
                user['session_id'] = str(retval['note_evaluation_collection'][0]['session_id'])
                user['class_eu_id'] = str(retval['note_evaluation_collection'][0]['class_eu_id'])

                class_ue_code = ""
                class_ue_titre = ""
                ue_data = MYSY_GV.dbname['unite_enseignement'].find_one({'_id':ObjectId(str(user['class_eu_id'])),
                                                                          'valide':'1',
                                                                          'locked':'0',
                                                                          'partner_owner_recid':str(my_partner['recid'])})
                if( "code" in ue_data.keys() ):
                    class_ue_code = str(ue_data['code'])
                if ("titre" in ue_data.keys()):
                    class_ue_titre = str(ue_data['titre'])

                user['class_ue_code'] = class_ue_code
                user['class_ue_titre'] = class_ue_titre


                user['type_eval_id'] = str(retval['note_evaluation_collection'][0]['type_eval_id'])
                type_eval_data = MYSY_GV.dbname['type_eval_id'].find_one({'_id':ObjectId(str(user['type_eval_id'])),
                                                                          'valide':'1',
                                                                          'locked':'0',
                                                                          'partner_owner_recid':str(my_partner['recid'])})
                if( type_eval_data and 'code' in type_eval_data.keys() ):
                    user['type_eval_code'] = type_eval_data['code']
                else:
                    user['type_eval_code'] = ""


                user['eval_date_heure_debut'] = str(retval['note_evaluation_collection'][0]['eval_date_heure_debut'])
                user['eval_date_heure_fin'] = str(retval['note_evaluation_collection'][0]['eval_date_heure_fin'])

                user['nom'] = nom_apprenant
                user['prenom'] = prenom_apprenant
                user['email'] = email_apprenant
                user['id'] = str(nb_val)
                if( "note" not in retval.keys() ):
                    user['note'] = "-1"

                user['class_id'] = str(retval['note_evaluation_collection'][0]['class_id'])
                myclass_data = MYSY_GV.dbname['myclass'].find_one({'_id':ObjectId(str(user['class_id'])),
                                                                   'valide':'1',
                                                                   'locked':'0',
                                                                   'partner_owner_recid':str(my_partner['recid'])},
                                                                  {'_id':1, 'external_code':1, "title":1 })

                """
                Insertion des data dans le fichier excel
                """
                column = 0
                row = row + 1

                # Champ : Titre de la formation
                Formation = ""
                if (myclass_data and "title" in myclass_data.keys()):
                    Formation = myclass_data['title']

                worksheet.write(row, column, Formation)
                column += 1

                # Champ : session_code (classe dans la formation initiale)
                mysession_data = MYSY_GV.dbname['session_formation'].find_one({'_id': ObjectId(str(user['session_id'])),
                                                                   'valide': '1',
                                                                   'partner_owner_recid': str(my_partner['recid'])},
                                                                  {'_id': 1, 'code_session': 1, })
                code_session = ""
                if (mysession_data and "code_session" in mysession_data.keys()):
                    code_session = mysession_data['code_session']

                worksheet.write(row, column, code_session)
                column += 1

                # Champ : Nom
                worksheet.write(row, column, nom_apprenant)
                column += 1

                # Champ : prenom_apprenant
                worksheet.write(row, column, prenom_apprenant)
                column += 1

                # Champ : email_apprenant
                worksheet.write(row, column, email_apprenant)
                column += 1

                # Champ : UE Code
                worksheet.write(row, column, class_ue_code)
                column += 1

                # Champ : class_ue_titre
                worksheet.write(row, column, class_ue_titre)
                column += 1

                # Champ : note_evaluation_code
                worksheet.write(row, column,  user['note_evaluation_code'] )
                column += 1

                # Champ :  user['eval_date_heure_debut']
                worksheet.write(row, column,  user['eval_date_heure_debut'])
                column += 1

                # Champ :  user['eval_date_heure_fin']
                worksheet.write(row, column, user['eval_date_heure_fin'])
                column += 1

                # Champ :  user['note']
                worksheet.write(row, column, user['note'])
                column += 1


                nb_val = nb_val + 1



        workbook.close()
        if os.path.exists(outputFilename):
            # print(" ### ok os.path.exists(outputFilename) "+str(outputFilename))
            return True, send_file(outputFilename, as_attachment=True)

        return False, " Impossible de générer l'export  (2) "



    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 générer l'export for "


"""
Fonction qui permet d'exporter les notes dans un fichier excel 
"""

def Export_To_Excel_List_Participant_To_Evaluation(diction):
    try:
        diction = mycommon.strip_dictionary(diction)

        """
        Verification des input acceptés
        """
        field_list = ['token', 'evaluation_id', ]

        incom_keys = diction.keys()
        for val in incom_keys:
            if val not in field_list and val.startswith('my_') is False:
                mycommon.myprint(str(
                    inspect.stack()[0][3]) + "  Le champ  '" + val + "' n'est pas autorisé")
                return False, " Les informations fournies sont incorrectes"

        """
        Verification des champs obligatoires
        """
        field_list_obligatoire = ['token', 'evaluation_id', ]

        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, " Les informations fournies sont incorrectes"

        """
        Verification de l'identité et autorisation de l'entité qui
        appelle cette API
        """
        token = ""
        if ("token" in diction.keys()):
            if diction['token']:
                token = diction['token']

        local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
        if (local_status is not True):
            return local_status, my_partner

        """
        Verifier que l'evaluation est valide
        """
        is_evaluation_valide = MYSY_GV.dbname['note_evaluation'].count_documents(
            {"_id": ObjectId(str(diction['evaluation_id'])),
             'valide': '1',
             'locked': '0',
             'partner_owner_recid': str(my_partner['recid'])})

        if (is_evaluation_valide != 1):
            mycommon.myprint(
                str(inspect.stack()[0][3]) + " L'identifiant de l'évaluation n'est pas valide  ")
            return False, " L'identifiant de l'évaluation n'est pas valide "

        evaluation_data = MYSY_GV.dbname['note_evaluation'].find_one(
            {"_id": ObjectId(str(diction['evaluation_id'])),
             'valide': '1',
             'locked': '0',
             'partner_owner_recid': str(my_partner['recid'])})

        RetObject = []
        val_tmp = 0

        ts = datetime.now().timestamp()
        ts = str(ts).replace(".", "").replace(",", "")[-5:]

        orig_file_name = "Export_Reponse_" + str(ts) + ".xlsx"
        outputFilename = str(MYSY_GV.TEMPORARY_DIRECTORY) + "/" + str(orig_file_name)

        tab_exported_fields_header = ["formation", "classe", "evaluation_code","evaluation_titre",
                                      "evaluation_eval_date_heure_debut", "evaluation_eval_date_heure_fin", "nom_apprenant",
                                      "prenom_apprenant", "email_apprenant", "evaluation_note",]


        # Create a workbook and add a worksheet.
        workbook = xlsxwriter.Workbook(outputFilename)
        worksheet = workbook.add_worksheet()

        nb_val = 0
        row = 0
        column = 0

        evaluation_formation = ""
        evaluation_code_session = ""

        # Recuperer les données de la formation
        qry_class = {'_id': ObjectId(str(evaluation_data['class_id'])),
                                                         'valide': '1', 'locked': '0',
                                                         'partner_owner_recid': str(my_partner['recid'])}

        class_data = MYSY_GV.dbname['myclass'].find_one({'_id': ObjectId(str(evaluation_data['class_id'])),
                                                         'valide': '1', 'locked': '0',
                                                         'partner_owner_recid': str(my_partner['recid'])})

        if (class_data and "title" in class_data.keys()):
            evaluation_formation = class_data['title']


        # Recuperation des données de la session
        session_data = MYSY_GV.dbname['session_formation'].find_one(
            {'_id': ObjectId(str(evaluation_data['session_id'])),
             'valide': '1',
             'partner_owner_recid': str(my_partner['recid'])})

        if (session_data and "code_session" in session_data.keys()):
            evaluation_code_session = session_data['code_session']

        """
                Creation de l'entete du fichier excel
                """

        for header_item in tab_exported_fields_header:
            worksheet.write(row, column, header_item)
            column += 1

        """
        Creation des data du fichier excel
        """
        for retval in MYSY_GV.dbname['note_evaluation_participant'].find(
                {'evaluation_id': str(diction['evaluation_id']),
                 'valide': '1',
                 'locked': '0',
                 'partner_owner_recid': str(my_partner['recid']),
                 }):


            user = retval
            nom_apprenant = ""
            prenom_apprenant = ""
            email_apprenant = ""
            groupe = ""


            if ("inscription_id" in retval and retval['inscription_id']):
                # Recuprer les données de l'inscrit
                inscription_data = MYSY_GV.dbname['inscription'].find_one(
                    {'_id': ObjectId(str(retval['inscription_id']))},
                    {'_id': 1, 'apprenant_id': 1})

                apprenant_data = MYSY_GV.dbname['apprenant'].find_one(
                    {'_id': ObjectId(str(inscription_data['apprenant_id']))},
                    {'_id': 1, 'nom': 1, 'prenom': 1, 'email': 1})

                nom_apprenant = apprenant_data['nom']
                prenom_apprenant = apprenant_data['prenom']
                email_apprenant = apprenant_data['email']




            user['nom'] = nom_apprenant
            user['prenom'] = prenom_apprenant
            user['email'] = email_apprenant
            user['id'] = str(nb_val)
            if ("note" not in retval.keys()):
                user['note'] = "-1"

            nb_val = nb_val + 1

            column = 0
            row = row + 1

            # Champ : formation
            worksheet.write(row, column, evaluation_formation)
            column += 1

            # Champ : classe / evaluation_code_session
            worksheet.write(row, column, evaluation_code_session)
            column += 1

            # Champ : evaluation_code
            worksheet.write(row, column, str(evaluation_data['code']))
            column += 1

            # Champ : evaluation_titre
            worksheet.write(row, column, str(evaluation_data['titre']))
            column += 1


            # Champ : evaluation_eval_date_heure_debut
            worksheet.write(row, column, str(evaluation_data['eval_date_heure_debut']))
            column += 1

            # Champ : evaluation_eval_date_heure_fin
            worksheet.write(row, column, str(evaluation_data['eval_date_heure_fin']))
            column += 1


            # Champ : nom
            worksheet.write(row, column, user['nom'])
            column += 1

            # Champ : prenom
            worksheet.write(row, column, user['prenom'])
            column += 1

            # Champ : email
            worksheet.write(row, column, user['email'])
            column += 1

            # Champ : note
            worksheet.write(row, column, user['note'])
            column += 1



        workbook.close()
        if os.path.exists(outputFilename):
            # print(" ### ok os.path.exists(outputFilename) "+str(outputFilename))
            return True, send_file(outputFilename, as_attachment=True)


        return False, "Impossible de générer l'export  (2) "


    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
        return False, " Impossible de générer l'export "

