# -*- coding:utf-8 -*-
"""
/***************************************************************************
 dict_email.py

 DictLayout class allows to send link to answer in an email


        begin                : 2020-07-22
        git sha              : $Format:%H$
        copyright            : (C) 2020 by Jean-Marie Arsac
        email                : jmarsac@azimut.fr
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
 """

# use python3

import smtplib
from email.headerregistry import Address
from email.message import EmailMessage
from email.utils import make_msgid

from qgis.core import Qgis

from .utils import Utils


class DictEmail(object):
    def __init__(self, server, port, user, security=""):
        self.server = server
        self.user = user
        self.security = security
        self.port = port
        self.sender_name, self.sender_domain = user.split("@")
        self.sender_surname = ""
        self.receiver = ""
        self.setSubject()
        # corps du mail en texte
        self.text_body = ""
        # corps du mail en HTML
        self.html_body = ""

    def setSenderSurname(self, surname):
        self.sender_surname = surname

    def setSubject(self, subject: str = "Récépissé DT/DICT/ATU"):
        self.subject = subject

    def setTextBody(self, text_body):
        self.text_body = text_body

    def setHtmlBody(self, html_body):
        self.html_body = html_body

    def buildAndSendMail(
        self,
        password,
        receiver_email,
        iface=None,
        save_it: bool = False,
        receiver_fullname: str = "",
    ):

        receiver_name, receiver_domain = receiver_email.split("@")
        if not receiver_fullname:
            receiver_fullname = receiver_name
        # Create the base text message.
        msg = EmailMessage()
        msg["Subject"] = self.subject
        msg["From"] = Address(self.sender_surname, self.sender_name, self.sender_domain)
        msg["To"] = Address(receiver_fullname, receiver_name, receiver_domain)
        msg["Message-ID"] = make_msgid()

        textBody = Utils.expandVariablesInString(self.text_body)
        msg.set_content(textBody)

        htmlBody = Utils.expandVariablesInString(self.html_body)

        # Add the html version.  This converts the message into a multipart/alternative
        # container, with the original text message as the first part and the new html
        # message as the second part.
        msg.add_alternative(htmlBody, subtype="html")
        s = None
        if password:
            try:
                if self.security == "SSL/TLS":
                    s = smtplib.SMTP_SSL(self.server, self.port)
                else:
                    s = smtplib.SMTP(self.server, self.port)
                smtp_ie = 0
                # s.set_debuglevel(True)
                # identify ourselves, prompting server for supported features
                s.ehlo()

                # If we can encrypt this session, do it
                if self.security == "STARTTLS" and s.has_extn("STARTTLS"):
                    s.starttls()
                    s.ehlo()  # re-identify ourselves over TLS connection

                s.login(self.user, password)
                smtp_ie = s.send_message(msg)
                s.quit()
                if iface:
                    iface.messageBar().pushMessage(
                        "Courriel envoyé à {}@{}".format(
                            receiver_name, receiver_domain
                        ),
                        "",
                        Qgis.Success,
                        10,
                    )
                if save_it:
                    self.raw_message = bytes(msg)
                return True

            except Exception as e:
                if s:
                    s.quit()
                if iface:
                    iface.messageBar().pushMessage(
                        "impossible d'envoyer le courriel à {}@{}".format(
                            receiver_name, receiver_domain
                        ),
                        str(e),
                        Qgis.Critical,
                        10,
                    )
                else:
                    print(str(e))
            return False

    @classmethod
    def checkSmtpAccount(
        cls,
        iface=None,
        server="",
        port="",
        user="",
        password="",
        security="",
        silent=True,
    ):
        s = None
        if server == "":
            server = "?"
        if user == "":
            user = "?"
        try:
            if security == "SSL/TLS":
                s = smtplib.SMTP_SSL(server, int(port))
            else:
                s = smtplib.SMTP(server, int(port))
            smtp_ie = 0
            # s.set_debuglevel(True)
            # identify ourselves, prompting server for supported features
            s.ehlo()

            # If we can encrypt this session, do it
            if security == "STARTTLS" and s.has_extn("STARTTLS"):
                s.starttls()
                s.ehlo()  # re-identify ourselves over TLS connection

            s.login(user, password)
            s.quit()
            if not silent:
                if iface:
                    iface.messageBar().pushMessage(
                        "Connection de {} sur {} réussie".format(user, server),
                        "",
                        Qgis.Success,
                        10,
                    )
                else:
                    print("Connection de {} sur {} réussie".format(user, server))
            return True

        except Exception as e:
            if s:
                s.quit()
            if not silent:
                if iface:
                    iface.messageBar().pushMessage(
                        "Echec de la connection de {} sur {}".format(user, server),
                        str(e),
                        Qgis.Critical,
                        10,
                    )
                else:
                    print(str(e))

        return False

    @classmethod
    def defaultTextBody(cls):
        return """\
@dict_tvx_description
    
Madame, monsieur,
    
Vous pouvez télécharger les fichiers de réponse à votre demande en utilisant le lien suivant.

<@dict_url_reponse>

Pour cela, copiez le dans votre navigateur et validez.

Cordialement.

L'équipe DT/DICT
"""

    @classmethod
    def defaultHtmlBody(cls):
        return """\
<html><head></head>
<body>
@dict_tvx_description
<br /><br />
Madame, monsieur,
<br /><br />
Vous pouvez télécharger les <a href="@dict_url_reponse">fichiers de réponse à votre demande</a>. 
<br /><br />
Cordialement.
<br /><br />
L'équipe DT/DICT
<br />
</body>
</html>
"""
