from __future__ import print_function
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import locale
import datetime
import inspect
import sys, os

from bson import ObjectId
from pymongo import ReturnDocument

import prj_common as mycommon
import GlobalVariable as MYSY_GV
from dateutil import tz
import pytz
import sib_api_v3_sdk
from sib_api_v3_sdk.rest import ApiException
import jinja2
from email.message import EmailMessage

configuration = sib_api_v3_sdk.Configuration()
configuration.api_key['api-key'] = MYSY_GV.SENDINBLUE_API_KEY_SUPPORT

api_instance = sib_api_v3_sdk.TransactionalEmailsApi(sib_api_v3_sdk.ApiClient(configuration))

locale.setlocale(category=locale.LC_ALL, locale='fr_FR.utf8')



smtp_address = 'smtp-relay.sendinblue.com'
port = 587
sender = 'support@mysy-training.com'
receiver = ["cbalde3@mysy-training.com","billardman1@gmail.com"]


user = 'support@mysy-training.com'
password = 'Tut29488!+'


"""
Envoi de l'email de confirmation d'inscription à une formation
"""
def incription_training_confirmation_mail(diction):
    try:

        print(" ### incription_training_confirmation_mail = "+str(diction))
        """
        Verification de la liste des champs obligatoires
        """
        field_list_obligatoire = ['nom', 'prenom', 'email', 'date_du', 'date_au', 'adresse', 'title']
        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, "Impossible d'envoyer l'email de confirmation de l'inscritpion"



        tomorrow = datetime.date.today() + datetime.timedelta(days=1)
        tomorrow_day = tomorrow.strftime("%A")

        print("debut envoi mail de test ")

        """
        Verification si c'est une formation en ligne.
        auquel cas, l'adresse est du type : enligne"""

        print(" ### Adresse = "+str(diction['adresse']) )
        adresse_session = str(diction['adresse'])
        trim_adr = str(diction['adresse']).strip().replace(" ","").lower()
        if (trim_adr == "enligne"):
            adresse_session = "enligne"

        """
        send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(template_id=1, params={ "nom": str(diction['nom']),
                                                                               "prenom":str(diction['prenom']),
                                                                               "date_du": str(diction['date_du']),
                                                                               "date_fin": str(diction['date_au']),
                                                                               "adresse": str(diction['adresse']),
                                                                               "title":str(diction['title'])},
                                                       to=to, bcc=bcc )
        """

        print("debut envoi mail de test ")
        # on rentre les renseignements pris sur le site du fournisseur

        # msg = MIMEMultipart("alternative")
        smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port)
        msg = EmailMessage()

        # JINJA2
        templateLoader = jinja2.FileSystemLoader(searchpath="./")
        templateEnv = jinja2.Environment(loader=templateLoader)
        TEMPLATE_FILE = "Template/MySy_confirmation_inscription_formation_tpl.html"
        template = templateEnv.get_template(TEMPLATE_FILE)
        # This data can come from database query
        body = {

            "params" :{"nom": str(diction['nom']),
                      "prenom": str(diction['prenom']),
                      "date_du": str(diction['date_du']),
                      "date_fin": str(diction['date_au']),
                      "adresse": str(adresse_session),
                      "title": str(diction['title']),
                       "email": str(diction['email'])},
        }

        sourceHtml = template.render(params=body["params"])

        msg.set_content(sourceHtml, subtype='html')


        msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User
        msg['Cc'] = 'contact@mysy-training.com'
        msg['Subject'] = '[MySy Training]: Confirmation inscription formation'
        msg['To'] = str(diction['email'])


        smtpserver.ehlo()
        smtpserver.starttls()
        smtpserver.login(MYSY_GV.O365_SMTP_COUNT_user, MYSY_GV.O365_SMTP_COUNT_password)
        val = smtpserver.send_message(msg)
        smtpserver.close()
        print(" Email confirlation envoyé " + str(val))


        return True, " Email confirlation inscritpion bien envoyé"

    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno))
        return False, " Impossible d'envoyer l'email de notification "



"""
Envoi de l'email de refus d'une d'inscription à une formation
"""
def incription_training_refused_mail(diction):
    try:

        print(" ### incription_training_refused_mail = "+str(diction))
        """
        Verification de la liste des champs obligatoires
        """
        field_list_obligatoire = ['nom', 'prenom', 'email', 'date_du', 'date_au', 'adresse', 'title']
        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, "Impossible d'envoyer l'email de refus de l'inscritpion"



        tomorrow = datetime.date.today() + datetime.timedelta(days=1)
        tomorrow_day = tomorrow.strftime("%A")

        print("debut envoi mail de test ")

        """
        Verification si c'est une formation en ligne.
        auquel cas, l'adresse est du type : enligne"""

        print(" ### Adresse = "+str(diction['adresse']) )
        adresse_session = str(diction['adresse'])
        trim_adr = str(diction['adresse']).strip().replace(" ","").lower()
        if (trim_adr == "enligne"):
            adresse_session = "enligne"

        print("debut envoi mail de test ")
        # on rentre les renseignements pris sur le site du fournisseur

        # msg = MIMEMultipart("alternative")
        smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port)
        msg = EmailMessage()

        # JINJA2
        templateLoader = jinja2.FileSystemLoader(searchpath="./")
        templateEnv = jinja2.Environment(loader=templateLoader)
        TEMPLATE_FILE = "Template/MySy_refus_inscription_formation_tpl.html"
        template = templateEnv.get_template(TEMPLATE_FILE)
        # This data can come from database query
        body = {}
        if ("comment" in diction.keys()):
            if diction['comment']:
                body = {

            "params" :{"nom": str(diction['nom']),
                      "prenom": str(diction['prenom']),
                      "date_du": str(diction['date_du']),
                      "date_fin": str(diction['date_au']),
                      "adresse": str(adresse_session),
                      "title": str(diction['title']),
                      "email": str(diction['email']),
                      "comment": str(diction['comment'])},
            }

        else:
            body = {

                "params": {"nom": str(diction['nom']),
                           "prenom": str(diction['prenom']),
                           "date_du": str(diction['date_du']),
                           "date_fin": str(diction['date_au']),
                           "adresse": str(adresse_session),
                           "title": str(diction['title']),
                           "email": str(diction['email'])},
            }

        sourceHtml = template.render(params=body["params"])

        msg.set_content(sourceHtml, subtype='html')


        msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User
        msg['Cc'] = 'contact@mysy-training.com'
        msg['Subject'] = '[MySy Training]: Inscription formation refusée'
        msg['To'] = str(diction['email'])


        smtpserver.ehlo()
        smtpserver.starttls()
        smtpserver.login(MYSY_GV.O365_SMTP_COUNT_user, MYSY_GV.O365_SMTP_COUNT_password)
        val = smtpserver.send_message(msg)
        smtpserver.close()
        print(" Email confirlation envoyé " + str(val))


        return True, " Email confirlation inscritpion bien envoyé"

    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno))
        return False, " Impossible d'envoyer l'email de notification "



"""
Email de pre-inscription
"""
def Pre_incription_training_confirmation_mail(diction):
    try:

        print(" ### Preincription_training_confirmation_mail = "+str(diction))
        """
        Verification de la liste des champs obligatoires
        """
        field_list_obligatoire = ['nom', 'prenom', 'email', 'date_du', 'date_au', 'adresse', 'title']
        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, "Impossible d'envoyer l'email de confirmation de l'inscritpion"



        tomorrow = datetime.date.today() + datetime.timedelta(days=1)
        tomorrow_day = tomorrow.strftime("%A")

        print("debut envoi mail de test ")
        # on rentre les renseignements pris sur le site du fournisseur

        msg = MIMEMultipart("alternative")

        msg['Subject'] = 'MySy Training : pre-inscription formation'
        msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User
        msg['To'] = str(diction['email'])


        print(" ### Adresse = "+str(diction['adresse']) )

        # msg = MIMEMultipart("alternative")
        msg = EmailMessage()
        smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port)


        # JINJA2
        templateLoader = jinja2.FileSystemLoader(searchpath="./")
        templateEnv = jinja2.Environment(loader=templateLoader)
        TEMPLATE_FILE = "Template/MySy_confirmation_Pre_inscription_formation_tpl.html"
        template = templateEnv.get_template(TEMPLATE_FILE)
        # This data can come from database query
        body = {
            "params":{"nom": str(diction['nom']),
                      "prenom": str(diction['prenom']),
                      "date_du": str(diction['date_du']),
                      "date_fin": str(diction['date_au']),
                      "adresse": str(diction['adresse']),
                      "title": str(diction['title']),
                      "email": str(diction['email'])},
        }

        sourceHtml = template.render(params=body["params"])

        msg.set_content(sourceHtml, subtype='html')

        msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User
        msg['Cc'] = 'contact@mysy-training.com'
        msg['Subject'] = '[MySy Training] : pre-inscription formation'
        msg['To'] = str(diction['email'])

        smtpserver.ehlo()
        smtpserver.starttls()
        smtpserver.login(MYSY_GV.O365_SMTP_COUNT_user, MYSY_GV.O365_SMTP_COUNT_password)
        val = smtpserver.send_message(msg)
        smtpserver.close()
        print(" Email envoyé " + str(val))

        return True, " Email bien envoyé"

    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno))
        return False, " Impossible d'envoyer l'email de notification "


"""
Cet email envoie une notfication au l'institut de formation (partenair) 
Pour l'informer qu'un utilisateur s'est pre-inscrit
"""
def Notification_partner_Pre_incription_mail(diction):
    try:

        print(" ### Notification_partner_Pre_incription_mail = "+str(diction))
        """
        Verification de la liste des champs obligatoires
        """
        field_list_obligatoire = ['nom', 'prenom', 'email', 'date_du', 'date_au', 'adresse', 'title',
                                  'partner_mail', 'employeur', 'telephone']
        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, "Impossible d'envoyer l'email de confirmation de l'inscritpion"



        tomorrow = datetime.date.today() + datetime.timedelta(days=1)
        tomorrow_day = tomorrow.strftime("%A")

        print("debut envoi mail de test ")
        # on rentre les renseignements pris sur le site du fournisseur

        msg = MIMEMultipart("alternative")

        msg['Subject'] = 'MySy Training : pre-inscription formation'
        msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User
        msg['To'] = str(diction['email'])


        #print(" ### Adresse = "+str(diction['adresse']) )

        # msg = MIMEMultipart("alternative")
        msg = EmailMessage()
        smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port)


        # JINJA2
        templateLoader = jinja2.FileSystemLoader(searchpath="./")
        templateEnv = jinja2.Environment(loader=templateLoader)
        TEMPLATE_FILE = "Template/MySy_Notif_Partner_Pre_inscription_formation_tpl.html"
        template = templateEnv.get_template(TEMPLATE_FILE)
        # This data can come from database query
        body = {
            "params":{"nom": str(diction['nom']),
                      "prenom": str(diction['prenom']),
                      "date_du": str(diction['date_du']),
                      "date_fin": str(diction['date_au']),
                      "adresse": str(diction['adresse']),
                      "title": str(diction['title']),
                      "employeur": str(diction['employeur']),
                      "telephone": str(diction['telephone']),
                      "email": str(diction['email'])},
        }

        sourceHtml = template.render(params=body["params"])

        msg.set_content(sourceHtml, subtype='html')

        msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User

        msg['Cc'] = 'contact@mysy-training.com, billardman01@hotmail.com'


        msg['Subject'] = '[MySy Training] : pre-inscription à la formation '+str(diction['title'])
        msg['To'] = str(diction['partner_mail'])

        smtpserver.ehlo()
        smtpserver.starttls()
        smtpserver.login(MYSY_GV.O365_SMTP_COUNT_user, MYSY_GV.O365_SMTP_COUNT_password)
        val = smtpserver.send_message(msg)
        smtpserver.close()
        print(" Email envoyé " + str(val))

        return True, " Email bien envoyé"

    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno))
        return False, " Impossible d'envoyer l'email de notification "

"""
Envoi de l'email d'evaluation
"""
def Evaluation_training_confirmation_mail(diction):
    try:

        print(" ### Evaluation_training_confirmation_mail = " + str(diction))
        """
        Verification de la liste des champs obligatoires
        """
        field_list_obligatoire = ['nom', 'prenom', 'email', 'date_du', 'date_au', 'adresse', 'title', 'token_eval', 'internal_url']
        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, "Impossible d'envoyer l'email de confirmation de l'inscritpion"



        tomorrow = datetime.date.today() + datetime.timedelta(days=1)
        tomorrow_day = tomorrow.strftime("%A")

        print("debut envoi mail de test ")
        # on rentre les renseignements pris sur le site du fournisseur

        msg = MIMEMultipart("alternative")

        msg['Subject'] = 'MySy Training : Evaluation formation'
        msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User
        msg['To'] = str(diction['email'])

        my_url = ""
        if (MYSY_GV.MYSY_ENV == "PROD"):
            my_url = "https://www.mysy-training.com/Display-Detail-formation/" + str(diction['internal_url'])+"/"+str(diction['token_eval'])
        elif (MYSY_GV.MYSY_ENV == "DEV"):
            my_url = "http://localhost:3009/Display-Detail-formation/" + str(diction['internal_url'])+"/"+str(diction['token_eval'])
        elif (MYSY_GV.MYSY_ENV == "REC"):
            my_url = "https://dev.mysy-training.com/Display-Detail-formation/" + str(diction['internal_url'])+"/"+str(diction['token_eval'])

        print(" ### Adresse = "+str(diction['adresse']) )

        # msg = MIMEMultipart("alternative")
        msg = EmailMessage()
        smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port)


        # JINJA2
        templateLoader = jinja2.FileSystemLoader(searchpath="./")
        templateEnv = jinja2.Environment(loader=templateLoader)
        TEMPLATE_FILE = "Template/MySy_Evaluation_Class_tpl.html"
        template = templateEnv.get_template(TEMPLATE_FILE)
        # This data can come from database query
        body = {
            "params":{"nom": str(diction['nom']),
                      "prenom": str(diction['prenom']),
                      "date_du": str(diction['date_du']),
                      "date_fin": str(diction['date_au']),
                      "adresse": str(diction['adresse']),
                      "title": str(diction['title']),
                      "email": str(diction['email']),
                   "mysyurl": str(my_url)} }

        sourceHtml = template.render(params=body["params"])

        msg.set_content(sourceHtml, subtype='html')

        msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User
        msg['Cc'] = 'contact@mysy-training.com'
        msg['Subject'] =  'MySy Training : Evaluation formation : '+str(diction['title'])
        msg['To'] = str(diction['email'])

        smtpserver.ehlo()
        smtpserver.starttls()
        smtpserver.login(MYSY_GV.O365_SMTP_COUNT_user, MYSY_GV.O365_SMTP_COUNT_password)
        val = smtpserver.send_message(msg)
        smtpserver.close()
        print(" Email envoyé " + str(val))

        return True, " Email bien envoyé"

    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno))
        return False, " Impossible d'envoyer l'email de demande d'evaluation "


"""
Cette fonction envoi l'attestion par email
"""
def SendAttestion_to_attendee_by_email(diction):
    try:
        """
               Verification de la liste des champs obligatoires
               """
        field_list_obligatoire = ['nom', 'prenom', 'email', 'date_du', 'date_au', 'adresse', 'title',
                                  'attestation_tmpl', 'inscription_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, "Impossible d'envoyer l'attestation par email "


        print(' ###  diction = ',str(diction))

        msg = MIMEMultipart("alternative")


        msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User
        msg['To'] = str(diction['email'])


        # msg = MIMEMultipart("alternative")
        msg = EmailMessage()
        smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port)

        # JINJA2
        templateLoader = jinja2.FileSystemLoader(searchpath="./")
        templateEnv = jinja2.Environment(loader=templateLoader)
        TEMPLATE_FILE = "Template/"+ str(diction['attestation_tmpl']) +".html"

        template = templateEnv.get_template(TEMPLATE_FILE)
        # This data can come from database query
        body = {
            "params": {"nom": str(diction['nom']),
                       "prenom": str(diction['prenom']),
                       "date_du": str(diction['date_du']),
                       "date_fin": str(diction['date_au']),
                       "adresse": str(diction['adresse']),
                       "title": str(diction['title']),
                       "email": str(diction['email']),
                       }}

        sourceHtml = template.render(json_data=body["params"])

        msg.set_content(sourceHtml, subtype='html')

        msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User
        msg['Cc'] = 'contact@mysy-training.com'
        msg['Subject'] = 'MySy Training : Votre attestation de formation : ' + str(diction['title'])
        msg['To'] = str(diction['email'])

        smtpserver.ehlo()
        smtpserver.starttls()
        smtpserver.login(MYSY_GV.O365_SMTP_COUNT_user, MYSY_GV.O365_SMTP_COUNT_password)
        val = smtpserver.send_message(msg)
        smtpserver.close()
        print(" Email envoyé " + str(val))

        mytoday = datetime.date.today().strftime("%d/%m/%Y")
        my_local_mydata = {'certification_send_date':str(mytoday)}

        print(" ### str(diction['inscription_id']) = ",str(diction['inscription_id']) )
        ## Mise à jour de la date d'envoi du certificat
        MYSY_GV.dbname['inscription'].find_one_and_update({'_id':ObjectId(str(diction['inscription_id']))},
                                                           {"$set":my_local_mydata},
                                                          return_document=ReturnDocument.AFTER,)


        return True, " Email bien envoyé"

    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno))
        return False, " Impossible d'envoyer l'attestation par email "
