# -*- coding: utf-8 -*-
'''
Created on Jun 14, 2013

@author: ymh

Reminder :
You need to have the request context processor.

TEMPLATE_CONTEXT_PROCESSORS = (
...
'django.core.context_processors.request',
...
)

'''

from django import template
from .utils import easy_tag

register = template.Library()


class AppendParamNode(template.Node):
    def __init__(self, *params):
        
        self.dict_pairs = {}
        for dict_str in params:        
            if dict_str:
                for pair in dict_str.split(','):
                    pair = pair.split('=')
                    self.dict_pairs[pair[0]] = template.Variable(pair[1])
            
    def render(self, context):
        get = context['request'].GET.copy()

        for key in self.dict_pairs:
            get[key] = self.dict_pairs[key].resolve(context)
        
        path = ""
        if len(get):
            path = get.urlencode()
        
        return "?"+path if path else ""

@register.tag()
@easy_tag
def append_to_param(_tag_name, *params):
    return AppendParamNode(*params)


class HiddenParamFilterForm(template.Node):
    
    def __init__(self, form_var, *excluded_fields):
        self.form = template.Variable(form_var)
        self.excluded_fields = [template.Variable(f) for f in excluded_fields]
        
    def render(self, context):
        form = self.form.resolve(context)
        excluded_fields = [f.resolve(context) for f in self.excluded_fields]
        term_filter_hidden = dict([(k,v) for k,v in context['request'].GET.items() if k not in form.fields and v is not None and k not in excluded_fields])
        form_hidden_inputs = ""
        for name, value in term_filter_hidden.items():
            form_hidden_inputs += "<input type=\"hidden\" name=\"%s\" value=\"%s\"/>" % (name, value.replace("\"", "\\\""))

        return form_hidden_inputs
    
@register.tag()
@easy_tag
def hidden_param_filter(_tag_name, form_var, *excluded_fields):
    return HiddenParamFilterForm(form_var, *excluded_fields)

