"""
Created on 10.06.2012

@author: christian
"""
import copy

from django import template
from django.utils.datastructures import SortedDict


register = template.Library()


class FieldSetNode(template.Node):
    def __init__(self, form_variable, variable_name, fields):
        self.fields = fields
        self.variable_name = variable_name
        self.form_variable = form_variable

    def render(self, context):
        form = template.Variable(self.form_variable).resolve(context)
        new_form = copy.copy(form)
        # new_form.fields = SortedDict([(key, value) for key, value in
        # form.fields.items() if key in self.fields])
        new_form.fields = SortedDict(
            [(key, form.fields[key]) for key in self.fields]
        )
        context[self.variable_name] = new_form

        return u''


def get_fieldset(parser, token):
    try:
        _name_, fields, _from_, form, _as_, variable_name = \
            token.split_contents()
        fields = fields[1:-1]
        fields = [field.strip() for field in fields.split(',')]
    except ValueError:
        raise template.TemplateSyntaxError(
            'bad arguments for %r' % token.split_contents()[0]
        )
    return FieldSetNode(form, variable_name, fields)


get_fieldset = register.tag(get_fieldset)
