"""
Fonction commune des tableaux de bord comme :
- get_list_tbd
- add to my tbd
- remove from my tbd,
- etc
"""

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
from datetime import timedelta
from datetime import timedelta
import ast

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

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

        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 retval in MYSY_GV.dbname['base_config_dashbord'].find({'$or':[{'valide':"1", 'locked':'0', 'partner_owner_recid':'default'},
                                                                   {'valide':"1", 'locked':'0', 'partner_owner_recid':str(my_partner['recid'])} ]} ):
            RetObject.append(mycommon.JSONEncoder().encode(retval))


        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 tableaux de bord "


"""
Fonction ajoute un dashbord au dashbord de l'utilisateur
"""
def Add_To_User_Dashbord(diction):
    try:
        diction = mycommon.strip_dictionary(diction)

        """
        Verification des input acceptés
        """
        field_list = ['token',  "dashbord_internal_code",  "default_filter", "title", 'type_event',
                      'group_by']

        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',  "dashbord_internal_code",  "default_filter", ]

        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 dashbord existe
        is_existe_dashbord = MYSY_GV.dbname['base_config_dashbord'].count_documents({"dashbord_internal_code":str(diction['dashbord_internal_code']),
                                                                                     'valide':'1',
                                                                                     'locked':'0',
                                                                                     'partner_owner_recid':'default'
                                                                                     })

        if( is_existe_dashbord <= 0 ):
            mycommon.myprint(
                str(inspect.stack()[0][3]) + " Le code du tableau de bord est invalide ")
            return False, " Le code du tableau de bord est invalide "

        # S'assurer que le 'default_qery' est bien un json
        default_qery_Json = ast.literal_eval(diction['default_filter'])


        my_data = {}
        my_data['connected_id'] = str(my_partner['_id'])
        my_data['update_by'] = str(my_partner['_id'])
        my_data['partner_owner_recid'] = str(my_partner['recid'])
        my_data['default_filter'] = str(diction['default_filter'])
        if( "group_by" in diction.keys() ):
            my_data['group_by'] = str(diction['group_by'])
        else:
            my_data['group_by'] = ""

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

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

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


        return True, " Le tableau de bord a été correctement ajouté "


    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 tableau de bord "


"""
Fonction qui supprime un dashbord de la liste des dashbord de l'utilisateur
"""


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

        """
        Verification des input acceptés
        """
        field_list = ['token', "user_dashbord_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 = ['token', "user_dashbord_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 dashbord existe
        qry = {"_id": ObjectId(str(diction['user_dashbord_id'])),
             'valide': '1',
             'locked': '0',
             'partner_owner_recid': str(my_partner['recid'])
             }

        print(" ### qry = ", qry)
        is_existe_dashbord = MYSY_GV.dbname['user_dashbord'].count_documents(
            qry)

        if (is_existe_dashbord <= 0):
            mycommon.myprint(
                str(inspect.stack()[0][3]) + " Le code du tableau de bord est invalide ")
            return False, " Le code du tableau de bord est invalide "


        my_data = {}
        my_data['connected_id'] = str(my_partner['_id'])
        my_data['partner_owner_recid'] = str(my_partner['recid'])
        my_data['_id'] = ObjectId(str(diction['user_dashbord_id']))


        MYSY_GV.dbname["user_dashbord"].delete_one(my_data)


        return True, " Le tableau de bord 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 d'ajouter le tableau de bord "

"""
Recuperer la liste des tableaux de bord d'un user
"""
def Get_Connected_User_List_Dashbord(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

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

        print(" ### qry = ", qry)


        for retval in MYSY_GV.dbname['user_dashbord'].find( qry):


            """ 
             Convertion des filtres en date reelles.
             Par exemple m0 = mois en cours = 1 du mois en cours à la date du jours.
            """
            start_date = ""
            end_date = ""
            if( "default_filter" in retval.keys() ):
                local_default_filter = ast.literal_eval(retval['default_filter'])
                #print(" ### local_default_filter = ", local_default_filter)

                if( "periode" in local_default_filter.keys() and str(local_default_filter['periode']) == "m0" ):
                    local_status, start_current_month_date, end_current_month_date = mycommon.Get_Current_Month_Start_End_Date()
                    if( local_status is False):
                        return local_status, start_current_month_date

                    start_date = start_current_month_date
                    end_date = end_current_month_date
                    #print(" ### start_current_month_date = ", start_current_month_date, " ### end_current_month_date =", end_current_month_date)

                if ("periode" in local_default_filter.keys() and str(local_default_filter['periode']) == "m1"):
                    local_status, start_current_month_date, end_current_month_date = mycommon.Get_Previous_Month_Start_End_Date()
                    if (local_status is False):
                        return local_status, start_current_month_date

                    start_date = start_current_month_date
                    end_date = end_current_month_date
                    #print(" ### start_current_month_date = ", start_current_month_date, " ### end_current_month_date =", end_current_month_date)

                if ("session_start_date" in local_default_filter.keys() and "session_end_date" in local_default_filter.keys()):
                    start_date = local_default_filter['session_start_date']
                    end_date = local_default_filter['session_end_date']
                    #print(" ### start_date = ", start_date, " ### end_date =",end_date)



            if( "type_event" not in retval.keys() ) :
                retval['type_event'] = ""

            retval['start_date'] = start_date
            retval['end_date'] = end_date
            #print(" ### final retval = ", retval)
            RetObject.append(mycommon.JSONEncoder().encode(retval)) 

        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 tableaux de bord "
