from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import base64
import mimetypes
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from configmanager import configManager 
import requests
import json
from typing import List

class send_alert:
    def __inti__():
        self.configmng = configManager()

    def CreateMessageHtml(sender, to, subject, msgHtml, msgPlain, attachmentFile,date):
        print('***********************************\n')
        msg = MIMEMultipart('alternative')
        msg['Subject'] = subject
        msg['From'] = sender
        msg['To'] = to
        msg.attach(MIMEText(msgPlain, 'plain'))
        if True:
            msgPlain = msgPlain.replace("\n", "<br />\n")
            msgHtml = msgHtml.replace("\n", "<br />\n")
            msgHtml = """\
            <html>
            <head></head>
            <body>
                <p>{}
                </p>
                <p>{}
                </p>
            </body>
            </html>
            """.format(msgPlain,msgHtml)
        msg.attach(MIMEText(msgHtml, 'html'))
        if attachmentFile is not None:
            filename = 'BT_CH SKU Validation Summary for {}.csv'.format(date)
            attachment = MIMEApplication(attachmentFile)
            attachment['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
            msg.attach(attachment)
        
        return msg

    def send_email_oauth(sender, to, subject, msgHtml, msgPlain, attachmentFile, date):
        mail_creds = self.configmng.get_details('email_secret')
        username = mail_creds['username']
        password = mail_creds['password']

        connection = smtplib.SMTP(host='smtp.office365.com', port=587)
        connection.starttls()
        connection.login(username,password)
        try:
            msg= self.CreateMessageHtml(sender, to,subject, msgHtml, msgPlain, attachmentFile, date)
            connection.sendmail(msg['From'], msg['To'].split(','), msg.as_string())
            connection.quit()
        except Exception as e:
            print(e)

    def send_message_to_slack(channel, username, message):
    
        url = self.configmng.get_credentials('slackwebhook')['slack_webhook']
        payload={"channel": channel, "username": username, "text": message}
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        
        try:
            response = requests.post(url, headers=headers, data=json.dumps(payload))
        except:
            pass
        return None

    def send_alert_email_ses(subject:str, message: str,
                             source: str, destination : List ,
                              secret_string :str ='secrets'):

        keys= self.configmng.get_credentials(secret_string)
        client = boto3.client("ses", aws_access_key_id="",
                            aws_secret_access_key="", region_name="us-east-1")
        message = {"Subject": {"Data": subject}, "Body": {"Text": {"Data": message}}}
        response = client.send_email_oauth(Source=source,
                                            Destination={"ToAddresses": destination },
                                             Message=message)
