import calendar
from itertools import chain

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

from store_order.models import OrderItem, Order


def year_list(current_year, num_years=5):
    """ Return a list of years, starting at current year ending with
    (current year + num_years), the default is 5
    """
    return [(i, i) for i in range(current_year, current_year + num_years)]


def month_list():
    """ Return iterated list of months
    """
    return [(i, calendar.month_name[i]) for i in range(1, len(calendar.month_name))]


def get_renewals_by_user(user):
    """ Returns subscriptions (OrderItems) by user

        Each subscription
    """
    from accounts.subscriptions import Subscription

    if not user:
        return None

    ordered_items = get_subscriptions().filter(
        order__user=user, gift_detail__exact=None
    )
    order_items = list(chain(ordered_items))

    subscriptions = []
    for order_item in order_items:
        if order_item.product.child().renewal:
            subscriptions.append(
                Subscription(
                    order_item.product.title,
                    order_item.order.date,
                    order_item.product.child().duration,
                )
            )

    return subscriptions


def get_subscriptions_by_user(user):
    """ Returns subscriptions (OrderItems) by user

        Each subscription
    """
    from accounts.subscriptions import Subscription

    if not user:
        return None

    ordered_items = get_subscriptions().filter(
        order__user=user, gift_detail__exact=None
    )

    gifted_items = get_subscriptions().filter(gift_detail__email__iexact=user.email)

    order_items = list(chain(ordered_items, gifted_items))

    subscriptions = []
    for order_item in order_items:
        if not order_item.product.child().renewal:
            subscriptions.append(
                Subscription(
                    order_item.product.title,
                    order_item.order.date,
                    order_item.product.child().duration,
                )
            )

    return subscriptions


def get_subscriptions(order=None):
    """ Subscriptions are really OrderItems with a subscription product
    attached.
    """
    from catalog.models import Subscription

    order_items = OrderItem.objects.filter(
        product__subclass_type__iexact=Subscription.__name__.lower()
    )

    if order:
        order_items = order_items.filter(order=order)

    return order_items


def send_change_of_address_email(
    title, account_number, date_effective, date_from, date_to, old_address, new_address
):

    template = "storefront/change_of_address_email.html"
    DEFAULT_FROM_EMAIL = getattr(settings, "DEFAULT_FROM_EMAIL")
    NOTIFICATIONS_EMAIL = getattr(settings, "NOTIFICATIONS_EMAIL", [])
    subject, from_email, to = (
        "Change of Address Update",
        DEFAULT_FROM_EMAIL,
        NOTIFICATIONS_EMAIL,
    )

    data = {"old_address": old_address, "new_address": new_address}
    data.update({"title": title, "account_number": account_number})
    data.update(
        {"date_effective": date_effective, "date_from": date_from, "date_to": date_to}
    )

    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_account_email(email, password, user, profile, site):

    template = "storefront/new_account_email.html"
    DEFAULT_FROM_EMAIL = getattr(settings, "DEFAULT_FROM_EMAIL")
    subject, from_email, to = ("New Account", DEFAULT_FROM_EMAIL, email)

    data = {"email": email, "password": password, "site": site}
    data.update({"first_name": user.first_name, "last_name": user.last_name})
    data.update(
        {
            "company": profile.company,
            "address1": profile.address1,
            "address2": profile.address2,
            "city": profile.city,
            "region": profile.region,
            "phone": profile.phone,
            "country": profile.country,
        }
    )

    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()
