"""
Dans ce fichier on gere les paramettrage des stapes d'une session de formation
Ceci permet à chaque partner de definir ses propres etapes


"""

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


"""
Ajout d'un setup 
"""
def Add_Update_Partner_session_step(diction):
    try:
        diction = mycommon.strip_dictionary(diction)

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

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

        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 'session_step_sequence' est bien un entier
        local_status, local_val = mycommon.IsInt(str(diction['session_step_sequence']))
        if (local_status is False):
            mycommon.myprint(" La sequence doit être un nombre entier")
            return False, " La sequence doit être un nombre entier"


        my_data = {}
        my_data['partner_owner_recid'] = str(my_partner['recid'])
        my_data['session_step_name'] = str(diction['session_step_name'])
        my_data['session_step_sequence'] = str(diction['session_step_sequence'])

        if( "session_step_comment" in  diction.keys()):
            my_data['session_step_comment'] = str(diction['session_step_comment'])

        my_data['valide'] = "1"
        my_data['locked'] = "0"
        my_data['date_update'] =  str(datetime.now())

        # La clé de la mise à jour est :
        # my_data['partner_owner_recid']
        # my_data['session_step_name']

        result = MYSY_GV.dbname['base_partner_session_step'].find_one_and_update(
            {'partner_owner_recid': str(my_partner['recid']),
             'session_step_name' : str(diction['session_step_name'])},
            {"$set": my_data},
            return_document=ReturnDocument.AFTER,
            upsert=True,

        )

        return True, " La configuration a été correctement ajoutée / 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 d'ajouter la configuration "

"""
Suppression d'un point de configuraton à partir de l'_id
"""

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

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

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

        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

        # Verification de l'existance du point de paramettrage à supprimer
        Is_Setup_Exist = MYSY_GV.dbname['base_partner_session_step'].count_documents( {'partner_owner_recid': str(my_partner['recid']),
             'session_step_name': str(diction['session_step_name']), '_id':ObjectId(str(my_partner['_id'])),
                                                                                'valide':'1', 'locked':'0'})

        if( Is_Setup_Exist < 0 ):
            mycommon.myprint(
                str(inspect.stack()[0][3]) + " - La configuration  '" + str(
                    diction['session_step_name']) + "' n'est pas valide ")
            return False, "  La configuration  '" + str(diction['session_step_name']) + "' n'est pas valide "

        if (Is_Setup_Exist > 1):
            mycommon.myprint(
                str(inspect.stack()[0][3]) + " - La configuration  '" + str(
                    diction['session_step_name']) + "' correspond plusieurs documents. Suppression annulée ")
            return False, " La configuration  '" + str(
                    diction['session_step_name']) + "' correspond plusieurs documents. Suppression annulée "


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

        if (delete_data is None or delete_data.deleted_count < 0):
            mycommon.myprint(
                str(inspect.stack()[0][3]) + " - Impossible de supprimer le paramétrage (2) ")
            return False, " Impossible de supprimer le paramétrage (2)  ",


        return True, " Le parmétrage a été correctement supprimé"

    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 le paramétrage  "

"""
Recuperation de la liste des etapes de session d'un partenaire.

/!\ : Important : 
Si il ya au moins une étape appartenant à un partenaire, alors on considere que partner
a activé la gestion des etapes de session.

Si il n'y a aucune ligne de paramettrage valide, alors on va aller chercher les etapes par defaut.
"""
def Get_List_Partner_Or_Default_session_step(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

        """
        /!\ On regarde si le partnenaire a au moins une etape de session de parametter
        """
        is_partner_etape_session_count = MYSY_GV.dbname["base_partner_session_step"].count_documents({'partner_owner_recid':str(my_partner['recid']), 'valide':'1', 'locked':'0'})
        if( is_partner_etape_session_count > 0 ):
            RetObject = []
            val_tmp = 1
            for New_retVal in MYSY_GV.dbname['base_partner_session_step'].find(
                    {'partner_owner_recid': str(my_partner['recid']), 'valide': '1', 'locked': '0'}).sort(
                    [("session_step_sequence", pymongo.ASCENDING)]):
                user = New_retVal
                user['id'] = str(val_tmp)
                val_tmp = val_tmp + 1
                RetObject.append(mycommon.JSONEncoder().encode(user))

            return True, RetObject

        else:
            RetObject = []
            val_tmp = 1
            for New_retVal in MYSY_GV.dbname['base_partner_session_step'].find({'partner_owner_recid':"default", 'valide':'1', 'locked':'0'}).sort([("session_step_sequence", pymongo.ASCENDING)]):

                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 points de paramétrage "


"""
Recuperation de la liste des etapes de session d'un partenaire.

/!\ : Important : 
Ici on recuperer exclivement les données du partenaire
"""
def Get_List_Partner_session_step(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


        RetObject = []
        val_tmp = 1
        for New_retVal in MYSY_GV.dbname['base_partner_session_step'].find(
                {'partner_owner_recid': str(my_partner['recid']), 'valide': '1', 'locked': '0'}).sort(
            [("session_step_sequence", pymongo.ASCENDING)]):

            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 points de paramétrage "




"""
Recuperation des informations d'un point de parametrage donnée
"""
def Get_Given_Partner_session_step(diction):
    try:
        diction = mycommon.strip_dictionary(diction)

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

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

        if( str(diction['session_step_name']) not in MYSY_GV.PARTNER_BASE_session_step_name ):
            mycommon.myprint(
                str(inspect.stack()[0][3]) + " - La valeur '" + str(diction['session_step_name']) + "' n'est pas valide ")
            return False, " Point de parametrage "+ str(diction['session_step_name']) + " invalide "


        RetObject = []

        param_retval_value = ""

        qry_tva = {'partner_owner_recid':str(my_partner['recid']), 'valide':'1',
                                                                     'locked':'0', 'session_step_name':str(diction['session_step_name'])}

        #print(" ### qry_tva = ", qry_tva)
        for New_retVal in MYSY_GV.dbname['base_partner_session_step'].find({'partner_owner_recid':str(my_partner['recid']), 'valide':'1',
                                                                     'locked':'0', 'session_step_name':str(diction['session_step_name'])}):
            user = New_retVal
            param_retval_value = str(New_retVal['session_step_sequence'])


        """
        Si la valeur est vide, alors on va aller chercher la configuration par default
        """
        if( str(param_retval_value).strip() == ""):
            for New_retVal in MYSY_GV.dbname['base_partner_session_step'].find(
                    {'partner_owner_recid': "default", 'valide': '1',
                     'locked': '0', 'session_step_name': str(diction['session_step_name'])}):
                user = New_retVal
                param_retval_value = str(New_retVal['session_step_sequence'])

        retval_json = {}
        retval_json['session_step_name'] = str(diction['session_step_name'])
        retval_json['session_step_sequence'] = param_retval_value

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

        #print(" ### retval_json =", retval_json)
        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 points de paramétrage "
