from __future__ import absolute_import

import smtplib
from email import encoders
from email.charset import Charset, QP
from email.mime.text import MIMEText
from email.mime.nonmultipart import MIMENonMultipart
from email.mime.multipart import MIMEMultipart

# TODO(xavid): move this dependency to bazjunk
from bazbase.translators import guess_type

def format(msg, subject, from_addr, to_addr, cc=None, attachment=None):
    text = MIMEText(msg, 'plain', 'utf-8')
    if attachment is not None:
        from bazjunk.ext import unaccent
        msg = MIMEMultipart()
        msg.attach(text)
        filename, data, contenttype = attachment
        filename = unaccent.asciify(filename)
        if contenttype is None:
            contenttype = guess_type(filename)[0]
        maintype, subtype = contenttype.split('/', 1)
        att = MIMENonMultipart(maintype, subtype)
        att.set_payload(data)
        encoders.encode_base64(att)
        att.add_header('Content-Disposition', 'attachment', filename=filename)
        msg.attach(att)
    else:
        msg = text
    msg['Subject'] = subject
    msg['From'] = from_addr
    msg['To'] = to_addr
    if cc:
        msg['CC'] = cc
    return msg.as_string()

def send(msg, subject, from_addr, to_addr, smtp_server, cc=None,
         attachment=None):
    msg = format(msg, subject, from_addr, to_addr, cc, attachment)
    s = smtplib.SMTP(smtp_server)
    dests = [to_addr]
    if cc is not None:
        dests.append(cc)
    s.sendmail(from_addr, dests, msg)
    s.quit()
