from dataclasses import dataclass
import smtplib
import ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.utils import make_msgid
import config


@dataclass
class Message:
    mailto: str
    subject: str
    html: str
    attachment: list


class SMTP_365:
    def __init__(self, host='', port=0, local_hostname=None,
                 timeout=30,
                 source_address=None):
        pass

    def login(self, user, password, *, initial_response_ok=True):
        pass

    def sendmail(self, from_addr, to_addrs, msg, mail_options=(),
                 rcpt_options=()):
        pass


class mail:
    connected = False

    def __init__(self, cfg=None):
        self.cfg = cfg
        if cfg is None:
            self.cfg = config.Config()
        self.mail_cfg = self.cfg.smtp
        self.reply_to = self.cfg.kunde_safe + '@global-cube.com'
        self.context = ssl.create_default_context()

    def __enter__(self):
        try:
            if self.mail_cfg.secure == 'ssl':
                self.mailserver = smtplib.SMTP_SSL(self.mail_cfg.server, self.mail_cfg.port, context=self.context)
            else:
                self.mailserver = smtplib.SMTP(self.mail_cfg.server, self.mail_cfg.port)

            # self.mailserver.set_debuglevel(1)
            if self.mail_cfg.secure == 'tls':
                # self.context.options |= ssl.OP_NO_TLSv1_2 | ssl.OP_NO_TLSv1_3
                self.context.minimum_version = ssl.TLSVersion["TLSv1_2"]
                self.mailserver.ehlo()
                self.mailserver.starttls(context=self.context)

            self.mailserver.login(self.mail_cfg.username, self.mail_cfg.password)
            # self.mailserver.noop()
            self.connected = True
        except smtplib.SMTPException as e:
            print(e)
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.connected:
            self.mailserver.quit()

    def send(self, mailto, subject, html, attachment=None):
        msg = self.message(mailto, subject, html, attachment)
        msg['Message-ID'] = make_msgid(domain=self.mail_cfg.server)
        res = {'id': msg['Message-ID'], 'mailto': mailto, 'status': 'OK'}

        try:
            result = self.mailserver.sendmail(self.mail_cfg.email, mailto, msg.as_string())
            with open('mail.txt', 'w') as fwh:
                fwh.write(msg.as_string())
        except smtplib.SMTPException as e:
            print(e)
            pass

    def message(self, mailto, subject, html, attachment):
        msg = MIMEMultipart('alternative')
        msg['From'] = self.mail_cfg.email
        msg['To'] = mailto
        # msg['Reply-To'] = self.reply_to
        msg['Subject'] = subject

        # text = '\n'.join([x for x, _ in attachment])
        # msg.attach(MIMEText(text, 'plain'))
        msg.attach(MIMEText(html, 'html'))

        for name, filename in attachment or []:
            with open(filename, "rb") as f:
                part = MIMEApplication(f.read(), Name=name)
                part['Content-Disposition'] = f'attachment; filename="{name}"'
                msg.attach(part)
        return msg


if __name__ == '__main__':
    with mail() as m:
        m.send('robert.bedner@gmail.com', 'Test 123', 'kein Kommentar',
               [('Umsatz_Bruttoertrag_Aftersales.pdf', '/home/robert/projekte/python/Portal/Publish/daten/gaps_vers_tag/Umsatz_Bruttoertrag_Aftersales_0.pdf')])
