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

register = template.Library()


# convert reply codes to something fancy, either a image link
# or raw text (the bool in the tuple indicates this)
@register.filter(name='convert_reply_code')
def convert_reply_code(code_list, method_key):
    if method_key == 'Y' or method_key == 'F':
        return False, code_list[0],
    else:
        return True, code_list[0],


# technically, this is used more like 'has at least group...'
# since permissions are subsets
@register.filter(name='check_group')
def check_group(user, group_key):
    if user is not None:
        # admin needs no shitty groups eh
        if user.is_superuser:
            return True
        else:
            return user.user_group >= group_key
    else:
        return False  # not logged in at all, boo


# look up a field via key in model instance
@register.filter(name='field_lookup')
def field_lookup(model_instance, key):
    if hasattr(model_instance, 'get_%s_display' % key):  # catches all choice fields
        return getattr(model_instance, 'get_%s_display' % key)()  # note the function call
    else:
        return getattr(model_instance, key)


@register.filter(name='get_class')
def get_class(value):
    return value.__class__.__name__


# replace part of the query string (or set if not there), useful to
# keep the remaining query string intact
@register.simple_tag(name='url_replace')
def url_replace(request, field, value):
    dict_ = request.GET.copy()
    dict_[field] = value
    return dict_.urlencode()


@register.filter(name='field_type')
def field_type(field, model_instance):
    return model_instance._meta.get_field(field).__class__.__name__


@register.filter(name='dict_lu')
def dict_lu(dictionary, key):
    return dictionary[key]


@register.filter(name='value_or_nothing')
def value_or_nothing(value):
    # make sure to actually check for none and not just 'if not value...' since
    # an integer zero should actually get displayed
    if value is None:
        return mark_safe('&#8212;')
    else:
        return value


@register.simple_tag(name='nothing')
def nothing():
    return mark_safe('&#8212;')