from django import template
from django.utils.safestring import mark_safe
from django.conf import settings

register = template.Library()


@register.filter
def get_element(iterable, index):
    return iterable.get(index)

@register.filter
def index_element(iterable, index):
    return iterable[index]

@register.filter
def to_list(obj):
    return list(obj)

@register.filter
def sort(iterable):
    return iterable.sort()


@register.filter
def sort_by_attr(iterable, attr):
    result = sorted(iterable, key=lambda x: getattr(x, attr))
    return result


@register.filter
def sort_by_key(iterable, key):
    result = sorted(iterable, key=lambda x: x[key])
    return result


@register.filter
def widget_css_class(field, css_class):
    return field.as_widget(attrs={"class": css_class})


@register.filter
def widget_placeholder(field, value):
    return field.as_widget(attrs={"placeholder": value})


@register.simple_tag
def widget_attrs(field, **kwargs):
    return field.as_widget(attrs=kwargs)


@register.filter
def markdown(text):
    import markdown
    return mark_safe(markdown.markdown(text))


@register.filter
def subtract(value, arg):
    return value - arg


@register.filter
def add(value, arg):
    return value + arg


@register.simple_tag(takes_context=True)
def theme_url(context, filename):
    from ..utils import get_settings_upload_url
    return get_settings_upload_url(context['site'].id, filename)


@register.simple_tag
def optional_url(url_name, *args, **kwargs):
    from django.urls import reverse, NoReverseMatch
    try:
        return reverse(url_name, args=args, kwargs=kwargs)
    except NoReverseMatch:
        return '#unknown-url'

@register.filter
def is_checkbox(field):
    from django.forms import CheckboxInput
    return isinstance(field.field.widget, CheckboxInput)


@register.filter
def weight(value):
    return '%.1f kg' % value


@register.simple_tag
def create_list(*args):
    return args


@register.simple_tag
def create_dict(**kwargs):
    return kwargs


@register.simple_tag
def save(value):
    return value


@register.filter
def attrs_list(obj):
    return dir(obj)


@register.filter
def inspect(obj):
    attrs = dir(obj)
    result = dict()
    for attr in attrs:
        result[attr] = getattr(obj, attr)
    return result


@register.simple_tag
def split_str(value, delimiter=','):
    return value.split(delimiter)


@register.filter
def money(value):
    if hasattr(settings, 'PCART_CURRENCIES'):
        currency_config = settings.PCART_CURRENCIES.get(getattr(settings, 'PCART_DEFAULT_CURRENCY', 'default'))
        return currency_config.get('price_template', '%s') % value
    else:
        return value


# Querysets

@register.filter
def order_by(queryset, values):
    values_attrs = values.split(',')
    return queryset.order_by(*values_attrs)

# Liquid compatibility


@register.filter
def append(value, arg):
    """Appends characters to a string.
    Input:
        {{ 'sales' | append: '.jpg' }}
    Output:
        sales.jpg
    """
    return value + arg


@register.filter
def camelcase(value):
    """Converts a string into CamelCase.
    Input:
        {{ 'coming-soon' | camelcase }}
    Output:
        ComingSoon
    """
    chunks = value.split('-')
    return ''.join([x.title() for x in chunks])


@register.filter
def capitalize(value):
    """Capitalizes the first word in a string.
    Input:
        {{ 'capitalize me' | capitalize }}
    Output:
        Capitalize me
    """
    return value.title()


@register.filter
def downcase(value):
    """Converts a string into lowercase.
    Input
        {{ 'UPPERCASE' | downcase }}
    Output
        uppercase
    """
    return value.lower()


@register.filter
def escape(value):
    """Escapes a string.
    Input
        {{ "<p>test</p>" | escape }}
    Output
         <!-- The <p> tags are not rendered -->
        <p>test</p>"""
    import html
    return html.escape(value)


@register.filter
def upcase(value):
    return value.upper()

