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

from catalog.constants import (
    FOREIGN,
    SHIPPING_METHODS_LIST,
    SHIPPING_METHODS,
    SHIPPING_METHOD_FOREIGN,
)
from catalog.models import Subscription


def valid_subscription_options(shipping_type):
    """ Returns a dictionary of valid values based on the type  """
    options = dict(
        subscriptions=Subscription.objects.valid_options(shipping_type=shipping_type),
        durations=sorted(
            set(Subscription.objects.durations_value_list(shipping_type=shipping_type))
        ),
        titles=sorted(
            set(Subscription.objects.titles_value_list(shipping_type=shipping_type))
        ),
    )
    return options


def unique_tuples(values, reverse=False):
    """ Enumerate and remove duplicate sets of tuples """
    return [(i, value) for i, value in enumerate(sorted(set(values), reverse=reverse))]


def unique_titles(shipping_type=None):
    """ Returns a unique set of tuples which can be used for title choices
    """
    return unique_tuples(Subscription.objects.titles_value_list(shipping_type))


def unique_durations(shipping_type=None):
    """ Returns a unique set of tuples which can be used for duration choices
    """
    return unique_tuples(Subscription.objects.durations_value_list(shipping_type))


def unique_shipping_methods():
    return [(i, value) for i, value in enumerate(SHIPPING_METHODS_LIST)]


def unique_title_images():
    """ take set of title/images, flip them into a dictionary """
    title_images = {}
    subscriptions = Subscription.objects.title_images()
    for subscription in subscriptions:
        title_images.update({subscription["title"]: subscription["image"]})
    return title_images


def get_value_by_index(value_tuple, index):
    return value_tuple[int(index)][1]


def shipping_method_options(shipping_type):
    if shipping_type == FOREIGN:
        return SHIPPING_METHOD_FOREIGN

    return SHIPPING_METHODS
