from email import encoders
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from .config import KINDLE_EMAIL,AMAZON_EMAIL,SMTP_HOST_NAME,SMTP_PORT,EMAIL_PASSWORD
from .scaffold import *
from sys import exit

import smtplib


def setup_email(SMTP_PORT=587):
    '''

    :param SMTP_PORT: Default port used by GMail is 587 for non SSL. User can set a custom port.
    :return: SMTP Object to send email.

    '''
    try:
        smtpObj = smtplib.SMTP(SMTP_HOST_NAME, SMTP_PORT)
        if smtpObj.ehlo()[0]==250:
            try:
                smtpObj.starttls()
                log.info('Connection successful... Attempting to login...')
                smtpObj.login(AMAZON_EMAIL, EMAIL_PASSWORD)
                return smtpObj

            except smtplib.SMTPAuthenticationError:
                log.error('Please Check Authentication details')
                exit()
    except:
        log.error('Nodename nor servername not identified.')
        exit()

def send_email(mobi_file):
    '''

    :param mobi_file: path to mobi file generated by `ebook-convert`
    '''

    log.info('Attempting to establish connection with SMTP server : {} {}'.format(SMTP_HOST_NAME,SMTP_PORT))
    smtpObj = setup_email(SMTP_PORT)
    msg = MIMEMultipart()
    msg['From'] = AMAZON_EMAIL
    msg['To'] = KINDLE_EMAIL
    # As suggested here https://www.amazon.com/gp/help/customer/display.html?nodeId=201974220
    msg['Subject'] = "Convert"
    body = ""
    msg.attach(MIMEText(body, 'plain'))
    attachment = open(mobi_file, "rb")
    part = MIMEBase('application', 'octet-stream')
    part.set_payload((attachment).read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', "attachment; filename= %s" % mobi_file)
    msg.attach(part)
    text = msg.as_string()

    try:
        log.info('Sending mail')
        smtpObj.sendmail(AMAZON_EMAIL, KINDLE_EMAIL, text)
    except:
        log.info('Cannot sent email.')
        exit()

    log.info('Sent')
    log.info('Quitting SMTP Connection')
    return smtpObj.quit()

