"""
Ce fichier permet de gerer les abonnements d'un partenair.

"""

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


"""
Ajout d'un abonnement
"""
def Add_Abonnement(diction):
    try:
        diction = mycommon.strip_dictionary(diction)

        """
        Verification des input acceptés
        """
        field_list = ['token', "description", "creation_date", "periodicite", "stripe_subscription_id",
                      "last_payement_date", "last_payement_status", "last_payement_amount",
                      "next_payement_date", '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'existe pas")
                return False, " Les informations fournies sont incorrectes",

        """
        Verification des champs obligatoires
        """
        field_list_obligatoire = ['token', "description", "creation_date", "periodicite", "stripe_subscription_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']

        # Verifier la validité du token
        retval = mycommon.check_partner_token_validity("", token)

        if retval is False:
            return "Err_Connexion", " La session de connexion n'est pas valide"


        partner_recid = mycommon.get_parnter_recid_from_token(token)
        if (partner_recid is False):
            mycommon.myprint(
                str(inspect.stack()[0][3]) + " - partner_recid est KO. Les données de connexion sont incorrectes ")
            return False, " Vous n'etes pas autorisé à utiliser cette API "

        # Recuperation des données du partenaire
        local_status, my_partner = mycommon.get_partner_data_from_recid(partner_recid)
        if (local_status is False):
            mycommon.myprint(str(inspect.stack()[0][3]) + " - impossible de récupérer les données du partenaire")
            return False, str(inspect.stack()[0][3]) + "  - impossible de récupérer les données du partenaire. "

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

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

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

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

        local_status = mycommon.CheckisDate(creation_date)
        if (local_status is False):
            mycommon.myprint(
                str(inspect.stack()[0][
                        3]) + " - La creation_date debut n'est pas au format jj/mm/aaaa ")
            return False, " La creation_date debut n'est pas au format jj/mm/aaaa "


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

        local_status = mycommon.CheckisDate(last_payement_date)
        if (local_status is False):
            mycommon.myprint(
                str(inspect.stack()[0][
                        3]) + " - La last_payement_date de fin n'est pas au format jj/mm/aaaa ")
            return False, " La last_payement_date de fin n'est pas au format jj/mm/aaaa "



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

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

        local_status = mycommon.CheckisDate(next_payement_date)
        if (local_status is False):
            mycommon.myprint(
                str(inspect.stack()[0][
                        3]) + " - La next_payement_date de deliberation n'est pas au format jj/mm/aaaa ")
            return False, " La next_payement_date de deliberation n'est pas au format jj/mm/aaaa "


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

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


        """
        Verifier s'il n'y pas deja un abonnement  avec le meme stripe_subscription_id et partner_recid
        """
        tmp_count = MYSY_GV['abonnement'].count_documents({'stripe_subscription_id': str(stripe_subscription_id),
                                                            'valide': '1', 'partner_recid':my_partner['recid']})
        if (tmp_count > 0):
            mycommon.myprint(
                str(inspect.stack()[0][
                        3]) + " - Cet abonnement est deja enregistré : stripe_subscription_id = ", str(stripe_subscription_id))

            return False, " -  Cet abonnement est deja enregistré "

        data['partner_recid'] = my_partner['recid']
        data['valide'] = '1'
        data['locked'] = '0'

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


        return True, " L'abonnement 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 l'abonnement "


"""
Mise à jour d'un abonnement
"""
def Update_Abonnement(diction):

    try:
        diction = mycommon.strip_dictionary(diction)

        """
               Verification des input acceptés
               """
        field_list = ['token', "description", "creation_date", "periodicite", "stripe_subscription_id",
                      "last_payement_date", "last_payement_status", "last_payement_amount",
					  "next_payement_date", "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'existe pas")
                return False, " Les informations fournies sont incorrectes",

        """
        Verification des champs obligatoires
        """
        field_list_obligatoire = ['token', 'stripe_subscription_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()):
            token = diction['token']

        # Verifier la validité du token
        retval = mycommon.check_partner_token_validity("", token)

        if retval is False:
            return "Err_Connexion", " La session de connexion n'est pas valide"

        partner_recid = mycommon.get_parnter_recid_from_token(token)
        if (partner_recid is False):
            mycommon.myprint(
                str(inspect.stack()[0][3]) + " - partner_recid est KO. Les données de connexion sont incorrectes ")
            return False, " Vous n'etes pas autorisé à utiliser cette API "

        # Recuperation des données du partenaire
        local_status, my_partner = mycommon.get_partner_data_from_recid(partner_recid)
        if (local_status is False):
            mycommon.myprint(str(inspect.stack()[0][3]) + " - impossible de récupérer les données du partenaire")
            return False, str(inspect.stack()[0][3]) + "  - impossible de récupérer les données du partenaire. "

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

        data = {}

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

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

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

        local_status = mycommon.CheckisDate(last_payement_date)
        if (local_status is False):
            mycommon.myprint(
                str(inspect.stack()[0][
                        3]) + " - La next_payement_date de deliberation n'est pas au format jj/mm/aaaa ")
            return False, " La next_payement_date de deliberation n'est pas au format jj/mm/aaaa "

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

        local_status = mycommon.CheckisDate(next_payement_date)
        if (local_status is False):
            mycommon.myprint(
                str(inspect.stack()[0][
                        3]) + " - La next_payement_date de deliberation n'est pas au format jj/mm/aaaa ")
            return False, " La next_payement_date de deliberation n'est pas au format jj/mm/aaaa "


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

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

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

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



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

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

        inserted_id = ""
        result = MYSY_GV.dbname['abonnement'].find_one_and_update(
            data_cle,
            {"$set": data},
            upsert=False,
            return_document=ReturnDocument.AFTER
        )
        if ("_id" not in result.keys()):
            mycommon.myprint(
                " Impossible de mettre à jour l'abonnement : " + str(stripe_subscription_id))
            return False, " Impossible de mettre à jour l'abonnement: " + str(stripe_subscription_id) + "  "

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

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


"""
fonction de recuperation d'un appel d'offre
"""


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

        """
        Verification des input acceptés
        """
        field_list = ['token', 'nom', 'prenom', 'email', 'tel_mobile', 'date_naissance', 'adr_rue', 'adr_ville',
                      'adr_code_postal', 'adr_pays', 'candidats_id', 'cpny']
        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']

        # Verifier la validité du token
        retval = mycommon.check_partner_token_validity("", token)

        if retval is False:
            return "Err_Connexion", " La session de connexion n'est pas valide"

        # Recuperation des données du partenaire
        local_status, my_user = mycommon.get_user_data_from_token(token)
        if (local_status is False):
            mycommon.myprint(str(inspect.stack()[0][3]) + " - impossible de récupérer les données de l'utilisateur ")
            return False, str(inspect.stack()[0][3]) + "  - impossible de récupérer les données de l'utilisateur. "

        RetObject = []
        nb_val = 0

        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 candidats "
