"""
Ce document permet de gerer les "enquetes" avec utilisation des formulaires

"""
import ast

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


"""
Fontion pour recupérer les données d'une enquete données
"""

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

        """
        Verification des input acceptés
        """
        field_list = ['survey_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 = [ 'survey_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']



        RetObject = []
        val_tmp = 0

        qry = { 'statut':'1', 'valide': '1', 'locked': '0', '_id':ObjectId(str(diction['survey_id']))}

        print(" qry == ", qry)
        for New_retVal in MYSY_GV.dbname['survey'].find(qry).sort([("_id", pymongo.DESCENDING), ]):
            user = New_retVal
            user['id'] = str(val_tmp)
            val_tmp = val_tmp + 1


            class_title = ""
            session_code = ""
            session_title = ""
            session_code_date_debut = ""
            session_code_date_fin = ""


            if( "session_id" in New_retVal.keys() and New_retVal['session_id']):
                # On va recuperer les données de la session
                my_session_data = MYSY_GV.dbname['session_formation'].find_one( {"partner_owner_recid": str(New_retVal['partner_owner_recid']), 'valide': '1', '_id':ObjectId(str(New_retVal['session_id']))})
                if( my_session_data and "class_internal_url" in my_session_data.keys() ):
                    my_class_data = MYSY_GV.dbname['myclass'].find_one(
                        {"partner_owner_recid":str(New_retVal['partner_owner_recid']), 'valide': '1',
                         'internal_url': str(my_session_data['class_internal_url'])})

                    if( my_class_data and "title" in my_class_data.keys() ):
                        class_title = my_class_data['title']
                        session_code = my_session_data['code_session']
                        session_title = my_session_data['titre']
                        session_code_date_debut = my_session_data['date_debut']
                        session_code_date_fin = my_session_data['date_fin']


            user['class_title'] = class_title
            user['session_code'] = session_code
            user['session_title'] = session_title
            user['session_code_date_debut'] = session_code_date_debut
            user['session_code_date_fin'] = session_code_date_fin

            """
            Recuperation des données du formulaire (question) 
            """
            list_questions = []
            if( "formulaire_id" in New_retVal.keys() ):
                my_formulaire_data = MYSY_GV.dbname['formulaire'].find_one( {"partner_owner_recid": str(New_retVal['partner_owner_recid']), 'valide': '1', 'locked':'0', '_id':ObjectId(str(New_retVal['formulaire_id']))})

                if(my_formulaire_data and "list_questions" in my_formulaire_data.keys() ):
                    list_questions = my_formulaire_data['list_questions']

            user['list_questions'] = list_questions

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

        print(" ### RetObject = ", RetObject)
        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 les données "



"""
Cette fonction enregistrer le resultat d'un survey
"""

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

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

        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 = [ 'survey_id', "list_response" ]

        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']

        """
        Verifier que l'enquete est valide
        """
        qry = {'statut': '1', 'valide': '1', 'locked': '0', '_id': ObjectId(str(diction['survey_id']))}

        is_valide_survey = MYSY_GV.dbname['survey'].count_documents(qry)

        if( is_valide_survey <= 0 ):
            mycommon.myprint(
                str(inspect.stack()[0][3]) + " L'identifiant de l'enquête est invalide ")
            return False, " L'identifiant de l'enquête est invalide "


        JSON_user_response = ast.literal_eval(diction['list_response'])
        list_keys = list(JSON_user_response.keys())
        global_response = []
        for my_key in list_keys:
            question_id = my_key
            response = JSON_user_response[my_key]
            node = {"question_id":question_id, "response":response}
            global_response.append(node)



        """
        On va enregister les reponse et changer le statut 
        """
        mydata = {}
        mydata['date_update'] = str(datetime.now())
        mydata['date_reponse'] = str(datetime.now())
        mydata['statut'] = "2"
        mydata['user_response'] = global_response

        result = MYSY_GV.dbname['survey'].find_one_and_update(
            {'statut': '1', 'valide': '1', 'locked': '0', '_id': ObjectId(str(diction['survey_id']))},
            {"$set": mydata},
            upsert=False,
            return_document=ReturnDocument.AFTER
        )
        if (result is None or "_id" not in result.keys()):
            mycommon.myprint(
                " Impossible de mettre à jour le formulaire (2) ")
            return False, " Impossible de mettre à jour le formulaire (2)  "


        return True, " Le formulaire a été correctement mis à 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 d'enregister les informations  "



"""
Survey for enduser : Cette fonction créer une enquete en prenant à partir d'une liste d'inscrit
"""

def Add_Survey_Tab_Inscrit(diction):
    try:
        field_list_obligatoire = ['session_id', 'token', 'tab_ids', 'formulaire_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"

        my_token = ""
        if ("token" in diction.keys()):
            if diction['token']:
                my_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

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

        tab_my_inscription_ids = str(my_inscription_ids).split(",")
        for my_inscription_id in tab_my_inscription_ids:

            # Verifier que les inscriptions sont valides pour cette session
            qry = {'session_id': str(diction['session_id']),
                                                                        '_id':ObjectId(str(my_inscription_id)),
                                                                       'partner_owner_recid': str(my_partner['recid']),
                                                                      'valide':'1'}

            print(" qry2 === ", qry)
            tmp_count = MYSY_GV.dbname['inscription'].count_documents({'session_id': str(diction['session_id']),
                                                                        '_id':ObjectId(str(my_inscription_id)),
                                                                       'partner_owner_recid': str(my_partner['recid']),
                                                                      'valide':'1'})

            if (tmp_count <= 0):
                mycommon.myprint(str(inspect.stack()[0][3]) + " L'identifiant de l'apprenant est invalide ")
                return False, " L'identifiant de l'apprenant est invalide "


        """
        Verifier la valididé du formulaire 
        """
        is_valide_form = MYSY_GV.dbname['formulaire'].count_documents({'_id':ObjectId(str(diction['formulaire_id'])),
                                                                       'valide':'1',
                                                                       'locked':'0',
                                                                       'partner_owner_recid':str(my_partner['recid'])})

        if( is_valide_form <= 0 ):
            mycommon.myprint(
                str(inspect.stack()[0][
                        3]) + " L'identifiant du formulaire est invalide ")
            return False, "  L'identifiant du formulaire est invalide "



        """
        Les inscriptions etant toutes valides, on va preceder à la creation de l'enquete
        """
        for my_inscription_id in tab_my_inscription_ids:
            # Recuperation des données de l'inscript

            req = {'session_id': str(diction['session_id']),
                                                                         '_id':ObjectId(str(my_inscription_id)),
                                                                        'partner_owner_recid': str(my_partner['recid']),
                                                                        'valide': '1'
                                                                        }

            print(" ### req = ", req)
            local_Insc_retval = MYSY_GV.dbname['inscription'].find_one({'session_id': str(diction['session_id']),
                                                                         '_id':ObjectId(str(my_inscription_id)),
                                                                        'partner_owner_recid': str(my_partner['recid']),
                                                                        'valide': '1'
                                                                        })

            if(local_Insc_retval is None ):
                mycommon.myprint(str(inspect.stack()[0][3]) + " L'identifiant de l'inscrit est invalide ")
                return False, "  L'identifiant de l'inscrit est invalide "

            server_diction = {}
            server_diction['token'] = diction['token']
            server_diction['session_id'] = diction['session_id']
            server_diction['inscrit_id'] = str(local_Insc_retval['_id'])
            server_diction['formulaire_id'] = diction['formulaire_id']

            local_status, local_retval = Create_One_Survey_To_Inscrit(server_diction)
            if( local_status is False):
                return local_status, local_retval


        return True, " La demande d'enquete a été créé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 le formulaire "


"""
Cette fonction initialise (suppression et creation ) d'une enquete pour tous
les inscrits d'un session.
algorithm :
On supprime tous enregistrements avec le clé : 
- session_id, 
"""
def Init_Survey_Tab_For_All_Session_Inscrit(diction):
    try:
        field_list_obligatoire = ['session_id', 'token', 'formulaire_id', 'survey_type']

        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"

        my_token = ""
        if ("token" in diction.keys()):
            if diction['token']:
                my_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 session est valide
        """
        is_valide_session = MYSY_GV.dbname['session_formation'].count_documents({'_id':ObjectId(str(diction['session_id'])),
                                                                                 'valide':'1',
                                                                                 'partner_owner_recid':str(my_partner['recid'])})

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

        tab_my_inscription_ids = []

        for my_inscription_id in MYSY_GV.dbname['inscription'].find({'session_id': str(diction['session_id']),
                                                                     'partner_owner_recid': str(my_partner['recid']),
                                                                      'valide':'1'}):

            tab_my_inscription_ids.append(str(my_inscription_id['_id']))


        """
        Verifier la valididé du formulaire 
        """
        is_valide_form = MYSY_GV.dbname['formulaire'].count_documents({'_id':ObjectId(str(diction['formulaire_id'])),
                                                                       'valide':'1',
                                                                       'locked':'0',
                                                                       'partner_owner_recid':str(my_partner['recid'])})

        if( is_valide_form <= 0 ):
            mycommon.myprint(
                str(inspect.stack()[0][
                        3]) + " L'identifiant du formulaire est invalide ")
            return False, "  L'identifiant du formulaire est invalide "



        """
        Les inscriptions etant toutes valides, on va proceder à 
        1 - suppression des data existate et 
        2 - la creation de l'enquete
        """

        MYSY_GV.dbname['survey'].delete_many({'partner_owner_recid':str(my_partner['recid']),
                                              'session_id':str(diction['session_id']),
                                              'survey_type':str(diction['survey_type'])})



        for my_inscription_id in tab_my_inscription_ids:
            # Recuperation des données de l'inscript

            req = {'session_id': str(diction['session_id']),
                                                                         '_id':ObjectId(str(my_inscription_id)),
                                                                        'partner_owner_recid': str(my_partner['recid']),
                                                                        'valide': '1'
                                                                        }


            local_Insc_retval = MYSY_GV.dbname['inscription'].find_one({'session_id': str(diction['session_id']),
                                                                         '_id':ObjectId(str(my_inscription_id)),
                                                                        'partner_owner_recid': str(my_partner['recid']),
                                                                        'valide': '1'
                                                                        })

            if(local_Insc_retval is None ):
                mycommon.myprint(str(inspect.stack()[0][3]) + " L'identifiant de l'inscrit est invalide ")
                return False, "  L'identifiant de l'inscrit est invalide "

            server_diction = {}
            server_diction['token'] = diction['token']
            server_diction['session_id'] = diction['session_id']
            server_diction['inscrit_id'] = str(local_Insc_retval['_id'])
            server_diction['formulaire_id'] = diction['formulaire_id']
            server_diction['survey_type'] = diction['survey_type']


            local_status, local_retval = Create_One_Survey_To_Inscrit(server_diction)
            if( local_status is False):
                return local_status, local_retval


        return True, " La demande d'enquete a été créé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 le formulaire "





"""
Cette fonction envoi un formulaire pour inscrit
"""
def Create_One_Survey_To_Inscrit(diction):
    try:
        field_list_obligatoire = ['session_id', 'token', 'inscrit_id', 'formulaire_id', 'survey_type']

        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"

        my_token = ""
        if ("token" in diction.keys()):
            if diction['token']:
                my_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

        """
        Recuperer les données du formulaire
        """

        my_formulaire_data = MYSY_GV.dbname['formulaire'].find_one({'_id':ObjectId(str(diction['formulaire_id'])),
                                                                  'valide':'1',
                                                                  'locked':'0',
                                                                  'partner_owner_recid':str(my_partner['recid'])})

        if( my_formulaire_data is None):
            mycommon.myprint(
                str(inspect.stack()[0][
                        3]) + " L'identifiant du formulaire est invalide  ")
            return False, "  L'identifiant du formulaire est invalide "

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

        if (my_session_data is None):
            mycommon.myprint(
                str(inspect.stack()[0][
                        3]) + " L'identifiant de la session est invalide  ")
            return False, "  L'identifiant de la session est invalide  "


        """
        Recuperer les données de l'inscrit
        """
        my_inscrit_data = MYSY_GV.dbname['inscription'].find_one({'_id': ObjectId(str(diction['inscrit_id'])),
                                                                        'valide': '1',
                                                                        'locked': '0',
                                                                        'partner_owner_recid': str(
                                                                            my_partner['recid'])})

        if (my_inscrit_data is None):
            mycommon.myprint(
                str(inspect.stack()[0][
                        3]) + " L'identifiant de l'inscrit est invalide  ")
            return False, "  L'identifiant de l'inscrit est invalide    "



        new_survey_data = {}
        new_survey_data['email'] = my_inscrit_data['email']
        new_survey_data['nom'] = my_inscrit_data['nom']
        new_survey_data['prenom'] = my_inscrit_data['prenom']
        new_survey_data['formulaire_id'] = str(diction['formulaire_id'])
        new_survey_data['partner_owner_recid'] = str(my_partner['recid'])
        new_survey_data['session_id'] = str(diction['session_id'])
        new_survey_data['survey_type'] = str(diction['survey_type'])
        new_survey_data['date_envoi'] = ""

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

        new_survey_data['statut'] = "0"
        new_survey_data['type'] = "1"
        new_survey_data['date_update'] = str(datetime.now())
        new_survey_data['update_by'] = str(my_partner['_id'])
        new_survey_data['created_by'] = str(my_partner['_id'])

        inserted_id = MYSY_GV.dbname['survey'].insert_one(new_survey_data).inserted_id

        if (not inserted_id):
            mycommon.myprint(" Impossible de créer l'enquete  (2) ")
            return False, "  Impossible de créer l'enquete  (2)   "


        return True, " L'enquete a été créé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'enquete unitaire "



"""
Cette fonction permet d'envoyer la demande d'enquete à la personne concerné
"""

def Send_Survey_TabIds(diction):
    try:
        field_list_obligatoire = [ 'token', 'tab_ids']

        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"

        my_token = ""
        if ("token" in diction.keys()):
            if diction['token']:
                my_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

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

        tab_my_survey_ids = str(my_survey_ids).split(",")
        for my_survey_id in tab_my_survey_ids:

            # Verifier que les survey sont valides
            qry = {  '_id':ObjectId(str(my_survey_id)), 'partner_owner_recid': str(my_partner['recid']),'valide':'1', 'locked':'0'}

            print(" qry2 === ", qry)
            tmp_count = MYSY_GV.dbname['survey'].count_documents(qry)

            if (tmp_count <= 0):
                mycommon.myprint(str(inspect.stack()[0][3]) + " L'identifiant de l'enquete "+str(my_survey_id)+" invalide ")
                return False, " L'identifiant de l'enquete "+str(my_survey_id)+" invalide  "



        """
        Les enquete etant toutes valides, on va preceder à l'envoie des email de demande
        """
        """
                          Recuperation des parametre SMTP du partner si le client a decidé d'utiliser son propre smpt
                          """
        partner_own_smtp_value = "0"
        partner_own_smtp = MYSY_GV.dbname['base_partner_setup'].find_one(
            {'partner_owner_recid': str(my_partner['recid']),
             'config_name': 'partner_smtp',
             'valide': '1',
             'locked': '0'})

        if (partner_own_smtp and "config_value" in partner_own_smtp.keys()):
            partner_own_smtp_value = partner_own_smtp['config_value']

            if (str(partner_own_smtp_value) == "1"):
                partner_SMTP_COUNT_password = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(my_partner['recid']),
                     'config_name': 'smtp_user_pwd',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_smtpsrv = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(my_partner['recid']),
                     'config_name': 'smtp_server',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_user = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(my_partner['recid']),
                     'config_name': 'smtp_user',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_From_User = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(my_partner['recid']),
                     'config_name': 'smtp_count_from_name',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_port = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(my_partner['recid']),
                     'config_name': 'smtp_count_port',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])



        for my_survey_id in tab_my_survey_ids:
            # Recuperation des données de l'inscript

            qry = {  '_id':ObjectId(str(my_survey_id)), 'partner_owner_recid': str(my_partner['recid']),'valide':'1', 'locked':'0'}

            local_survey_retval = MYSY_GV.dbname['survey'].find_one(qry)

            if(local_survey_retval is None ):
                mycommon.myprint(str(inspect.stack()[0][3]) + " L'identifiant de l'inscrit est invalide ")
                return False, "  L'identifiant de l'inscrit est invalide "

            servey_url = MYSY_GV.CLIENT_URL_BASE + "Survey/" + str(local_survey_retval['_id'])

            html = """\
                            <html>
                              <body>
                                <p>Hi,<br>
                                  Merci de suivre l'enquete :""" + str(servey_url) + """ </p>
                                <p><a href="https://blog.mailtrap.io/2018/09/27/cloud-or-local-smtp-server">SMTP Server for Testing: Cloud-based or Local?</a></p>
                                <p> Feel free to <strong>let us</strong> know what content would be useful for you!</p>
                              </body>
                            </html>
                            """

            html_mime = MIMEText(html, 'html')

            # Creation de l'email à enoyer
            msg = MIMEMultipart("alternative")

            if (str(partner_own_smtp_value) == "1"):
                smtpserver = smtplib.SMTP(partner_SMTP_COUNT_smtpsrv, partner_SMTP_COUNT_port)
            else:
                smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port)


            if (str(partner_own_smtp_value) == "1"):
                msg.attach(html_mime)
                msg['From'] = partner_SMTP_COUNT_From_User
                msg['Bcc'] = 'contact@mysy-training.com'
                msg['Subject'] = " Demande d'enquete "
                # msg['to'] = "billardman01@hotmail.com"

                msg['to'] = str(local_survey_retval['email'])

                smtpserver.ehlo()
                smtpserver.starttls()
                smtpserver.login(partner_SMTP_COUNT_user, partner_SMTP_COUNT_password)

            else:
                msg.attach(html_mime)
                msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User
                msg['Bcc'] = 'contact@mysy-training.com'
                msg['Subject'] = " Demande d'enquete "
                # msg['to'] = "billardman01@hotmail.com"

                msg['to'] = str(local_survey_retval['email'])

                smtpserver.ehlo()
                smtpserver.starttls()
                smtpserver.login(MYSY_GV.O365_SMTP_COUNT_user, MYSY_GV.O365_SMTP_COUNT_password)

                val = smtpserver.send_message(msg)
                smtpserver.close()
                print(" Email envoyé " + str(val))

                """
                Mettre à jour l'enquete pour dire que c'est envoyé
                """
                now = str(datetime.now())

                qry = {'_id': ObjectId(str(my_survey_id)), 'partner_owner_recid': str(my_partner['recid']),
                       'valide': '1', 'locked': '0'}
                MYSY_GV.dbname['survey'].find_one_and_update(qry,
                                                             {'$set':{'statut':'1', 'date_update':str(now),
                                                                      'update_by':str(my_partner['_id']),
                                                                      'date_envoi':now}}
                                                             )


        return True, " Les demandes d'enquete ont été envoyées "


    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'envoyer les demande "



"""
Fonction pour Recuperer la liste des enquete avec les filtre suivant : 
- session_id,
- formulaire_type - ['pos', 'hot_eval', 'cool_eval']
"""
def Get_List_Survey_with_filter(diction):
    try:
        diction = mycommon.strip_dictionary(diction)

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

        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',]

        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 = {}
        if ("session_id" in diction.keys()):
            filt_session_id = {'session_id': str(diction['session_id'])}



        RetObject = []
        val_tmp = 0

        qry = {"partner_owner_recid": str(my_partner['recid']), 'valide': '1', 'locked': '0'}
        query_with_filter = {'$and': [qry, filt_session_id]}

        pipe_qry = ([
            {'$match': query_with_filter },
            {'$project': {  'valide': 0, 'locked': 0,  }},
            {'$lookup': {
                'from': 'formulaire',
                "let": {'formulaire_id': "$formulaire_id",
                        'partner_owner_recid': '$partner_owner_recid'},
                'pipeline': [
                    {'$match':
                        {'$expr':
                            {'$and':
                                [

                                    {'$eq': ["$_id", {'$convert': {
                                        'input': "$$formulaire_id",
                                        'to': "objectId",
                                        'onError': {'error': 'true'},
                                        'onNull': {'isnull': 'true'}
                                    }}]},

                                    {'$eq': ["$valide", "1"]},
                                    {'$eq': ["$type", str(diction['formulaire_type'])]},
                                    {'$eq': ["$partner_owner_recid", '$$partner_owner_recid']}

                                ]
                            }
                        }
                    },


                ],
                'as': 'formulaire'
            }
            },
            {
                '$unwind': '$formulaire'
            }
			    ])

        #print(" ### pipe_qry = ", pipe_qry)

        for New_retVal in MYSY_GV.dbname['survey'].aggregate(pipe_qry):
            user = New_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 formulaires "
