"""
Dans ce fichier on gere les paramettrage de base d'un partenaire.

On y stock les informations communes à tous les user rattachés au partner.

ex :
 - Taux de TVA
 - SMTP
 - La langue
 - Region
 - etc

 Ce fichier travaille principalement sur la collection : "base_partner_setup"


 /!\ 10/05/2024 :
 On ajoute le module concerné à la collection pour pouvoir gerer les parametrage liée à des modules specifique.
 on aura le champ : "related_collection" pour cela.



par exemple :
 - devis (point de parametrage :
    => relance auto
    => frequence,
    etc).

les parametrage generaux auront, le "related_collection" = "" vide ou inexistant

"""

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_Basic_Setup(diction):
    try:
        diction = mycommon.strip_dictionary(diction)

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

        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',  'config_name', 'config_value', 'related_collection']

        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['config_name']) not in MYSY_GV.PARTNER_BASE_CONFIG_NAME):
            mycommon.myprint(
                str(inspect.stack()[0][3]) + " - La configuration  '" + str(diction['config_name']) + "' n'est pas acceptée ")
            return False, "  La configuration  '" + str(diction['config_name']) + "' n'est pas acceptée "

        my_data = {}
        my_data['partner_owner_recid'] = str(my_partner['recid'])
        my_data['config_name'] = str(diction['config_name'])
        my_data['config_value'] = str(diction['config_value'])
        my_data['related_collection'] = str(diction['related_collection'])
        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['config_name']

        result = MYSY_GV.dbname['base_partner_setup'].find_one_and_update(
            {'partner_owner_recid': str(my_partner['recid']),
             'config_name' : str(diction['config_name']),
             'related_collection':str(diction['related_collection'])},
            {"$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 / mettre à jour la configuration "

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

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

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

        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', 'config_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_setup'].count_documents( {'partner_owner_recid': str(my_partner['recid']),
             'config_name': str(diction['config_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['config_name']) + "' n'est pas valide ")
            return False, "  La configuration  '" + str(diction['config_name']) + "' n'est pas valide "

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

        delete_data = MYSY_GV.dbname['base_partner_setup'].delete_one(
            {'partner_owner_recid': str(my_partner['recid']),
             'config_name': str(diction['config_name']), '_id': ObjectId(str(my_partner['_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 parametrage d'un partenaire
"""
def Get_List_Partner_Basic_Setup(diction):
    try:
        diction = mycommon.strip_dictionary(diction)

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

        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', 'related_collection']
        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_setup'].find({'partner_owner_recid':str(my_partner['recid']), 'valide':'1', 'locked':'0',
                                                                     'related_collection':str(diction['related_collection'])}):
            if( str(New_retVal['config_name']) == "smtp_user_pwd"):
                New_retVal['config_value'] = New_retVal['config_value'][:2]+"...."+str(New_retVal['config_value'])[-2:]

            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_Basic_Setup(diction):
    try:
        diction = mycommon.strip_dictionary(diction)

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

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


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



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


        RetObject = []

        param_retval_value = ""

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

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


        """
        Si la valeur est vide, alors on va aller chercher la configuration par default
        """
        if( str(param_retval_value).strip() == ""):

            qry_tva2 = {'partner_owner_recid': "default", 'valide': '1',
                     'locked': '0', 'config_name': str(diction['config_name']),
                      'related_collection':str(related_collection)}

            print(" ### qry_tva2 = ", qry_tva2)

            for New_retVal in MYSY_GV.dbname['base_partner_setup'].find(
                    {'partner_owner_recid': "default", 'valide': '1',
                     'locked': '0', 'config_name': str(diction['config_name']),
                      'related_collection':str(related_collection)}):
                user = New_retVal
                param_retval_value = str(New_retVal['config_value'])

        retval_json = {}
        retval_json['config_name'] = str(diction['config_name'])
        retval_json['config_value'] = 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 "
