"""
Ce fichier est dedié à la gestion des contact de tout type
Chaque ligne contriendra le nom de la collection du recid concerné
ex :
- id,
- related_collection
- relected_recid
- type (standard, livraison, facturation, etc)
- nom
- email
- telephone_fix
- telephone_mobile
- linkin,
- facebook
- adresse
- code_postal
- ville
- pays
"""

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 ast


"""
Ajout d'un contact
"""
def Add_Contact(diction):

    try:
        diction = mycommon.strip_dictionary(diction)

        """
        Verification des input acceptés
        """
        field_list = ['token', "raison_sociale", "nom", "siret", "tva", "email",
                      "telephone", "website", "comment",'adr_adresse', 'adr_code_postal',
                      'adr_ville', 'adr_pays',  'type', 'telephone_mobile', 'linkedin',
                      'facebook', 'twitter', 'related_collection',
                      'prenom', 'fonction', 'civilite', 'related_collection_owner_id', 'include_com']

        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',  "email", 'related_collection','related_collection_owner_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


        """
        Verification s'il n'existe pas un client du partenaire qui porte la meme adresse email
         """
        tmp_count = MYSY_GV.dbname['contact'].count_documents({'email': str(diction['email']),
                                                               'valide': '1', 'partner_recid': my_partner['recid']})
        if (tmp_count > 0):
            mycommon.myprint(
                str(inspect.stack()[0][
                        3]) + " - Il existe déjà un contact qui porte le même email principal  = " +str(diction['email']))

            return False, " - Vous avez  déjà un contact qui a le même email principal  "



        """
                Recuperation des données fournies en entrée
                """
        data = {}
        data['partner_recid'] = my_partner['recid']

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

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

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

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

        include_com = "0"
        if ("include_com" in diction.keys()):
            include_com = diction['include_com']
        data['include_com'] = include_com


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

        civilite = ""
        if ("civilite" in diction.keys()):
            if diction['civilite']:
                civilite = str(diction['civilite']).lower()
        data['civilite'] = civilite


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

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

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

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

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

        email = ""
        if ("email" in diction.keys()):
            if diction['email']:
                email = diction['email']
                if( mycommon.isEmailValide(email) is False):
                    mycommon.myprint(
                        str(inspect.stack()[0][
                                3]) + " - L'adresse email "+str(email)+" n'est pas valide")

                    return False, " - - L'adresse email "+str(email)+" n'est pas valide  "
        data['email'] = diction['email']


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

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


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

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

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

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

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


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

                if( type not in MYSY_GV.CONTACT_TYPE):
                    mycommon.myprint(
                        "- Le type de contact  "+str(type)+" n'est pas autorisé")
                    return False, "- Le type de contact  "+str(type)+" n'est pas autorisé"

        data['type'] = type

        related_collection = ""
        if ("related_collection" in diction.keys()):
            if diction['related_collection']:
                related_collection = diction['related_collection']
                data['related_collection'] = diction['related_collection']
                if (related_collection not in MYSY_GV.CONTACT_COLLECTION):
                    mycommon.myprint(
                        "- La collection   " + str(related_collection) + " n'accepte pas de contact")
                    return False,  "- La collection   " + str(related_collection) + " n'accepte pas de contact"

        data['related_collection'] = related_collection

        related_collection_owner_id = ""
        if ("related_collection_owner_id" in diction.keys()):
            related_collection_owner_id = str(diction['related_collection_owner_id'])
        data['related_collection_recid'] = str(related_collection_owner_id)


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

        # Creation du RecId
        data['recid'] = mycommon.create_user_recid()


        inserted_id = ""
        inserted_id = MYSY_GV.dbname['contact'].insert_one(data).inserted_id
        if (not inserted_id):
            mycommon.myprint(
                " Impossible de créer le contact ")
            return False, " Impossible de créer le contact   "


        return True, " Le contact a été correctement créé"

    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 le contact "


"""
Mise à jour d'un contact en se basant sur : 
- token (partner_recid)
- email
- related_collection

"""
def Update_Contact(diction):
    try:
        diction = mycommon.strip_dictionary(diction)

        """
               Verification des input acceptés
               """
        field_list = ['token', "raison_sociale", "nom", "prenom", "siret", "tva", "email",
                      "telephone", "website", "comment",'adr_adresse', 'adr_code_postal',
                      'adr_ville', 'adr_pays',  'type', 'telephone_mobile', 'linkedin',
                      'facebook', 'twitter', 'prenom', 'fonction', 'civilite',
                      '_id', 'include_com']


        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',  "email", '_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 le contact qu'on souhaite mettre à jour existe bien
                 """


        tmp_count = MYSY_GV.dbname['contact'].count_documents({'_id':ObjectId(str(diction['_id'])),
                                                               'partner_recid':str(my_partner['recid']),
                                                               'valide':'1',
                                                               'locked':'0'})
        if (tmp_count <= 0):
            mycommon.myprint(
                str(inspect.stack()[0][
                        3]) + " - L'identifiant du contact est invalide ")

            return False, " L'identifiant du contact est invalide "



        """
        Recuperation des données fournies en entrée
        """

        data_update = {}
        """
                        Recuperation des données fournies en entrée
                        """

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

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

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

        civilite = ""
        if ("civilite" in diction.keys()):
            civilite = diction['civilite']
            data_update['civilite'] = str(diction['civilite']).lower()

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


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

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

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

        civilite = ""
        if ("civilite" in diction.keys()):
            civilite = diction['civilite']
            data_update['civilite'] = str(diction['civilite']).lower()

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

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

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

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



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

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

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


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

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

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

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

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

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

        type = ""
        if ("type" in diction.keys()):
            type = diction['type']
            data_update['type'] = diction['type']
            if (type not in MYSY_GV.CONTACT_TYPE):
                mycommon.myprint(
                    "- Le type de contact  " + str(type) + " n'est pas autorisé")
                return False, "- Le type de contact  " + str(type) + " n'est pas autorisé"




        data_update['valide'] = '1'
        data_update['locked'] = '0'
        data_update['date_update'] = str(datetime.now())
        data_update['update_by'] = str(my_partner['_id'])



        inserted_id = ""
        result = MYSY_GV.dbname['contact'].find_one_and_update(
            {'_id': ObjectId(str(diction['_id'])),
             'partner_recid': str(my_partner['recid']),
             'valide': '1',
             'locked': '0'},
            {"$set": data_update},
            upsert=False,
            return_document=ReturnDocument.AFTER
        )

        if (result is None or "_id" not in result.keys()):
            mycommon.myprint(
                " Impossible de mettre à jour le contact : email ")
            return False, " Impossible de mettre à jour le contact "

        return True, " Le contact 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 de mettre à jour le contact "


"""
Recuperation de la liste des contacts d'une entité en se basant sur 
- related_collection
- token (partner_recid)
- related_collection_owner_id (s'il est fourni)

"""
def Get_List_Entity_Contact(diction):
    try:
        diction = mycommon.strip_dictionary(diction)

        """
        Verification des input acceptés
        """
        field_list = ['token', 'related_collection', 'related_collection_owner_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', '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
        """
                Clés de mise à jour 
                """
        data_cle = {}
        data_cle['partner_recid'] = str(my_partner['recid'])
        data_cle['related_collection'] = str(diction['related_collection'])

        if ("related_collection_owner_id" in diction.keys()):
            related_collection_owner_id = str(diction['related_collection_owner_id'])
            data_cle['related_collection_recid'] = str(related_collection_owner_id)

        data_cle['locked'] = "0"

        RetObject = []
        val_tmp = 1

        for retval in MYSY_GV.dbname['contact'].find(data_cle):
            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 contacts "


"""
Recuperation d'un contact donnée en se basant sur on token, email, related_collection, related_collection_recid
"""
def Get_Given_Contact(diction):
    try:
        diction = mycommon.strip_dictionary(diction)

        """
        Verification des input acceptés
        """
        field_list = ['token', '_id', 'related_collection', 'related_collection_owner_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', '_id', 'related_collection', 'related_collection_owner_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_recid'] = str(my_partner['recid'])
        data_cle['_id'] = ObjectId(str(diction['_id']))
        data_cle['related_collection'] = str(diction['related_collection'])
        data_cle['related_collection_recid'] = str(diction['related_collection_owner_id'])

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

        RetObject = []
        val_tmp = 1

        #print(" ### data_cle = ", data_cle)
        for retval in MYSY_GV.dbname['contact'].find(data_cle):
            user = retval
            user['id'] = str(val_tmp)
            val_tmp = val_tmp + 1
            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 le contact "


"""
Fonction de suppression d'un contact
"""
def Delete_Given_Contact(diction):
    try:
        diction = mycommon.strip_dictionary(diction)

        """
        Verification des input acceptés
        """
        field_list = ['token', '_id', 'related_collection', 'related_collection_owner_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', '_id', 'related_collection', 'related_collection_owner_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_recid'] = str(my_partner['recid'])
        data_cle['_id'] = ObjectId(str(diction['_id']))
        data_cle['related_collection'] = str(diction['related_collection'])
        data_cle['related_collection_recid'] = str(diction['related_collection_owner_id'])

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


        # Verifier la validité du contact
        is_contact_is_valide = MYSY_GV.dbname['contact'].count_documents(data_cle)

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

        # Supression à faire
        MYSY_GV.dbname['contact'].delete_one( data_cle)

        #print(" ### RetObject = ", RetObject)
        return True, " Le contact 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 contact "

