import sys
import string
import random
import smtplib
from pathlib import Path
from mailbox import Maildir
from email.message import EmailMessage
from email.utils import formatdate
from email.header import Header, make_header

from procat2.settings import EMAIL_HOST, EMAIL_HOST_USER, EMAIL_HOST_PASSWORD

import logging
log = logging.getLogger(__name__)


body_ok = """Hi,

Attached is a copy of your marked up catalog and a spreadsheet with
the articles you selected.

Enjoy,
ProCatalog Markup Bot
"""

body_missing = """Hi,

I couldn't find a pdf attached to your message.  I can't do much
without a marked up catalog pdf, so please include that when you try
again.

Thanks,
ProCatalog Markup Bot
"""

body_no_matches = """Hi,

I couldn't find any products marked in your pdf.  Make sure you're
using a ProCatalog pdf and that you've circled or otherwise scribbled
over some material images or SKUs before submitting.

Thanks,
ProCatalog Markup Bot
"""


def reply(frm, subj, xls_path, pdf_path):
    msg = EmailMessage()
    msg.set_content(body_ok)
    subj = f'Re: {subj}'

    with open(xls_path, 'rb') as fp:
        msg.add_attachment(fp.read(),
                           maintype='application',
                           subtype='vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                           filename=Path(xls_path).name)

    with open(pdf_path, 'rb') as fp:
        msg.add_attachment(fp.read(),
                           maintype='application',
                           subtype='pdf',
                           filename=Path(pdf_path).name)

    send(frm, subj, msg)


def reply_missing(frm, subj):
    msg = EmailMessage()
    msg.set_content(body_missing)
    subj = f'Re: {subj}'
    send(frm, subj, msg)


def reply_no_matches(frm, subj):
    msg = EmailMessage()
    msg.set_content(body_no_matches)
    subj = f'Re: {subj}'
    send(frm, subj, msg)


def send_error_email(subj, einfo):
    msg = EmailMessage()
    msg.set_content(einfo)
    send('error@procatalog.io', subj, msg)


def send(frm, subj, msg):
    msg['From'] = 'Keen ProCatalog Markup Bot <markup@procatalog.io>'
    msg['Reply-To'] = 'Keen ProCatalog Support <support@procatalog.io>'
    msg['To'] = frm
    msg['Bcc'] = 'alx-markup@procatalog.io'
    msg['Subject'] = Header(subj).encode()
    msg['Message-ID'] = msgid()
    msg['Date'] = formatdate()

    maildir = Maildir('/tmp/markup_submit_mail')
    maildir.add(msg.as_bytes())

    log.info(f'sending email to "{frm}": {subj}')

    with smtplib.SMTP(EMAIL_HOST) as s:
        s.starttls()
        s.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD)
        s.send_message(msg)


def msgid():
    rand = ''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase + string.digits, k=16))
    return f'<{rand}@markup.procatalog.io>'
