from django import template

register = template.Library()

@register.simple_tag(takes_context=True)
def param_url(context, param_name, value):
    params = context['request'].GET.copy()
    params[param_name] = value
    return '?%s' % params.urlencode()

@register.simple_tag(takes_context=True)
def sort_url(context, sort_column):
    PARAMETER = 'sort'
    params = context['request'].GET.copy()
    if PARAMETER in params:
        rev = '-%s' % sort_column
        if params[PARAMETER] == sort_column:
            params[PARAMETER] = rev
        elif params[PARAMETER] == rev:
            del params[PARAMETER]
        else:
            params[PARAMETER] = sort_column
    else:
        params[PARAMETER] = sort_column
    return '?%s' % params.urlencode()

@register.simple_tag(takes_context=True)
def sort_indicator(context, sort_column, up, down, none):
    PARAMETER = 'sort'
    params = context['request'].GET
    result = ''
    if PARAMETER in params:
        if sort_column in params[PARAMETER]:
            if params[PARAMETER].startswith('-'):
                result = up
            else:
                result = down
    return '<b>%s</b>' % result

FILTER_PARAMETER = 'filter'
@register.simple_tag(takes_context=True)
def filter_url(context, filter_column, *args):
    params = context['request'].GET.copy()
    filter_name = '%s_%s' % (FILTER_PARAMETER, filter_column)
    if args:
        params[filter_name] = args[0]
    elif filter_name in params:
        del params[filter_name]
    params['page'] = str(1)
    return '?%s' % params.urlencode()

@register.simple_tag(takes_context=True)
def remove_param_url(context, *args):
    params = context['request'].GET.copy()
    toremove = set()
    for prefix in args:
        for key in params.iterkeys():
            if key.startswith(prefix):
                toremove.add(key)
    for key in toremove:
        del params[key]
    params['page'] = 1
    return '?%s' % params.urlencode()
