from django import template

from catalog.constants import SHIPPING_TYPES, SHIPPING_METHODS
from catalog.models import Subscription

from django.conf import settings
from .. import utils

register = template.Library()
PREFIX = "storefront/tags/subscriptions/"


@register.inclusion_tag(PREFIX + "address_form.html")
def address_form(form, show_email_field=None):
    return {"form": form, "show_email_field": show_email_field}


@register.inclusion_tag(PREFIX + "form_table_row.html")
def subscription_form_table_row(form_field):
    return {"form_field": form_field}


@register.inclusion_tag(PREFIX + "form_list_title.html")
def subscription_form_list_title(form_field):
    return {"form_field": form_field}


@register.inclusion_tag(PREFIX + "form_list_duration.html")
def subscription_form_list_duration(form_field):
    return {"form_field": form_field}


@register.inclusion_tag(PREFIX + "form_shipping_method.html")
def subscription_form_shipping_method(form_field):
    return {"form_field": form_field}


@register.inclusion_tag(PREFIX + "availability_table.html")
def subscription_availability_table(type, first_class):
    options = utils.valid_subscription_options(type)
    options.update({"type": type, "first_class": first_class})

    return options


@register.inclusion_tag(PREFIX + "price.html")
def subscription_price(type, title, duration):
    price = Subscription.objects.find_price(type, title, duration, False)
    first_class_price = Subscription.objects.find_price(type, title, duration, True)
    return {"price": price, "first_class_price": first_class_price}


@register.filter
def image_for_title(title):
    """ returns an image block using the """
    try:
        image = utils.unique_title_images()[title]
    except KeyError:
        raise KeyError(
            "You must add am image in the admin for "
            "subscription '{0}'.".format(title)
        )
    return '<img src="{0}{1}" alt="{2}logo">'.format(settings.MEDIA_URL, image, title)


@register.filter
def humanize_shipping_method(method):
    for enum, humanize in SHIPPING_METHODS:
        if enum == method:
            return humanize


@register.filter
def humanize_subscription_type(type):
    for enum, humanize in SHIPPING_TYPES:
        if enum == type:
            return humanize


@register.filter
def humanize_duration(duration, capitalize=True, pluralize=True):
    humanized = ""
    years = int(duration) / 12
    months = int(duration) % 12
    if months > 0:
        if capitalize:
            humanized += "{0} Months".format(months)
        else:
            humanized += "{0} months".format(months)
    if years > 0:
        if capitalize:
            humanized += "{0} Year".format(years)
        else:
            humanized += "{0} year".format(years)
    if years > 1 and pluralize:
        humanized += "s"
    return humanized
