import email
from email.header import Header
from email.mime.text import MIMEText
import logging
import smtplib
from time import time
import textwrap

from pylons.i18n import _

from adhocracy import config
from adhocracy.lib import helpers as h, version

log = logging.getLogger(__name__)
ENCODING = 'utf-8'


def send(email_from, to_email, message):
    server = smtplib.SMTP(config.get('smtp_server'),
                          config.get_int('smtp_port'))
    # server.set_debuglevel(1)
    server.sendmail(email_from, [to_email], message)
    server.quit()


def to_mail(to_name, to_email, subject, body, headers={}, decorate_body=True,
            email_from=None, reply_to=None, name_from=None):
    try:
        if email_from is None:
            email_from = config.get('adhocracy.email.from')
        if name_from is None:
            name_from = config.get('adhocracy.site.name')

        if decorate_body:
            body = (_(u"Hi %s,") % to_name +
                    u"\r\n\r\n%s\r\n\r\n" % body +
                    _(u"Cheers,\r\n\r\n"
                      u"    the %s Team\r\n") %
                    config.get('adhocracy.site.name'))

        # wrap body, but leave long words (e.g. links) intact
        body = u'\n'.join(textwrap.fill(line, break_long_words=False,
                                        break_on_hyphens=False)
                          for line in body.split(u'\n'))

        msg = MIMEText(body.encode(ENCODING), 'plain', ENCODING)

        for k, v in headers.items():
            msg[k] = v

        subject = Header(subject.encode(ENCODING), ENCODING)
        msg['Subject'] = subject
        msg['From'] = _("%s <%s>") % (name_from, email_from)
        to = Header(u"%s <%s>" % (to_name, to_email), ENCODING)
        msg['To'] = to
        if reply_to is not None:
            msg['Reply-To'] = reply_to
        msg['']
        msg['Date'] = email.Utils.formatdate(time())
        msg['X-Mailer'] = "Adhocracy SMTP %s" % version.get_version()
        # log.debug("MAIL\r\n" + msg.as_string())
        send(email_from, to_email, msg.as_string())
    except Exception:
        log.exception("Sending mail failed.")


def to_user(to_user, subject, body, headers={}, decorate_body=True,
            email_from=None, reply_to=None, name_from=None):
    return to_mail(to_user.name, to_user.email, subject, body, headers,
                   decorate_body, email_from, reply_to, name_from)


def send_activation_link(user):
    url = h.base_url("/user/%s/activate?c=%s" % (user.user_name,
                                                 user.activation_code),
                     instance=None, absolute=True)
    body = _("this email is to check the email address you have provided. "
             "In order to confirm this email address, please open the link "
             "below in your browser:") + "\r\n\r\n  " + url
    to_user(user, _("Confirm your email address"), body)
