import json
import logging
import logging.handlers
import smtplib
from typing import Tuple, List


class BufferingSMTPHandler(logging.handlers.BufferingHandler):

    # BASED ON CODE DEFINED HERE:
    # https://gist.github.com/anonymous/1379446 LINKED OUT FROM THIS ISSUE:
    # https://stackoverflow.com/questions/1610845/collate-output-in-python-logging-memoryhandler-with-smtphandler

    def __init__(self,
                 server: Tuple[str, str],
                 credentials: Tuple[str, str],
                 fromaddr: str, toaddrs: List[str], subject: str, capacity: int):

        logging.handlers.BufferingHandler.__init__(self, capacity)
        self.mailhost = server[0]
        self.mailport = server[1]
        self.login = credentials[0]
        self.passwd = credentials[1]
        self.fromaddr = fromaddr
        self.toaddrs = toaddrs
        self.subject = subject
        self.setFormatter(logging.Formatter("%(asctime)s %(levelname)-5s %(message)s"))

    def flush(self):
        if len(self.buffer) > 0:
            try:
                port = self.mailport
                server = smtplib.SMTP(self.mailhost, port)
                msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (self.fromaddr, ','.join(self.toaddrs), self.subject)
                for record in self.buffer:
                    s = self.format(record)
                    print(s)
                    msg = msg + s + "\r\n"

                server.ehlo()
                server.starttls()
                server.login(self.login, self.passwd)
                server.sendmail(self.fromaddr, self.toaddrs, msg)
                server.quit()
            except:
                raise Exception("Error thrown in BufferingSMTPHandler")
            self.buffer = []