import logging

from django.core.mail import EmailMultiAlternatives
from django.conf import settings
from django.template.loader import render_to_string

from store_order.models import Order

LOG = logging.getLogger(__name__)


def _send_email(template, email, duration, paper):

    DEFAULT_FROM_EMAIL = getattr(settings, "DEFAULT_FROM_EMAIL")
    subject, from_email, to = ("Thank you", DEFAULT_FROM_EMAIL, email)

    data = {"duration": duration, "paper": paper}

    text_content = render_to_string(template, dictionary=data)
    html_content = render_to_string(template, dictionary=data)

    msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
    msg.attach_alternative(html_content, "text/html")
    msg.send()


def send_new_email(email, duration, paper):
    _send_email("storefront/new_subscription_email.html", email, duration, paper)


def send_gift_email(email, duration, paper):
    _send_email("storefront/gift_subscription_email.html", email, duration, paper)


def send_renewal_email(email, duration, paper):
    _send_email("storefront/renewal_subscription_email.html", email, duration, paper)


def send_subscription_email(order, email=None):
    """  sends a new subscription email for each subscription on the order """
    LOG.debug("Send Subscription Email: In")
    if order and isinstance(order, Order):

        if not email:
            user = order.user
            if user and not user.is_anonymous() and user.email:
                email = user.email
            else:
                LOG.debug(
                    "User is anonymous or email is empty, no email will " "be found."
                )
                return

        for sub_item in order.subscription_items:
            LOG.debug(
                "Found subscription item ({0})on order({1})".format(sub_item, order)
            )
            product = sub_item.product.child()

            is_renewal = product.renewal
            is_gift = sub_item.is_gift
            title = product.title
            duration = product.duration

            if is_renewal:
                LOG.debug("Sending renewal email to {0}...".format(email))
                send_renewal_email(email, duration, title)
            elif is_gift:
                LOG.debug("Sending gift email to {0}...".format(email))
                send_gift_email(email, duration, title)
            else:
                LOG.debug("Sending new email to {0}...".format(email))
                send_new_email(email, duration, title)
        LOG.debug("Send Subscription Email: Out")
    else:
        LOG.debug("Not an order: {0}".format(order))
