import logging
from premailer import Premailer

from django.conf import settings
from django.template import loader

from intranet.femida.src.tasks import send_email, send_sms
from intranet.femida.src.startrek.utils import add_comment
from intranet.femida.src.utils.translation import get_language

logger = logging.getLogger(__name__)


def notify(transport, template_name, context, **kwargs):
    """
    Шорткат для отправки нотификации куда бы то ни было
    kwargs передаются дальше как есть
    """
    transport_method_map = {
        'email': notify_by_email,
        'sms': notify_by_sms,
        'startrek': notify_by_startrek,
    }

    notify_method = transport_method_map.get(transport)

    if not notify_method:
        raise ValueError('Unexpected transport')

    body = loader.render_to_string(template_name, context)
    notify_method(body, **kwargs)


def notify_by_email(body, receiver, subject=None, initiator=None, reply_to=None, **kwargs):
    body = Premailer(body, remove_classes=True).transform()
    emails = [receiver.email] if hasattr(receiver, 'email') else [receiver]
    reply_to = reply_to.email if reply_to and hasattr(reply_to, 'email') else reply_to

    if initiator:
        from_email = '"(femida) {username} – {full_name}" <{email}>'.format(
            username=initiator.username,
            full_name=initiator.get_full_name(lang=get_language()),
            email=settings.DEFAULT_FROM_EMAIL,
        )
    else:
        from_email = '"femida" <{email}>'.format(email=settings.DEFAULT_FROM_EMAIL)

    send_email.delay(
        subject=subject,
        body=body,
        to=emails,
        from_email=from_email,
        reply_to=reply_to,
        **kwargs
    )


def notify_by_sms(body, receiver):
    phone = receiver.phone
    if not phone:
        logger.error(
            'Can\'t send SMS, because receiver `%s` does not have phone',
            receiver
        )
        return

    send_sms.delay(phone=phone, text=body)


def notify_by_startrek(body, key):
    add_comment(key, body)
