"""Adds the template tag {% get_fieldset ... %}."""
import copy
from collections import OrderedDict

from django import template

register = template.Library()


class FieldSetNode(template.Node):
    """ Generates a new template variable to acces the new formset. """

    def __init__(self, form_variable, variable_name, fields):
        """ Sets all arguments as attributes. """
        self.fields = fields
        self.form_variable = form_variable
        self.variable_name = variable_name

    def render(self, context):
        """ puts all form fileds in a fieldset called self.variable_name. """
        form = template.Variable(self.form_variable).resolve(context)
        new_form = copy.copy(form)
        new_form.fields = OrderedDict(
            [(key, form.fields[key]) for key in self.fields]
        )
        context[self.variable_name] = new_form
        return u''


@register.tag(name='get_fieldset')
def get_fieldset(parser, token):  # Ignore PyLintBear (W0613)
    """ Template tag to split a large form in smaller formsets. 
    SYNTAX: {% get_fieldset "field1,field2,... from form as formset %}

    "field1,field2,...": a comma seperated list of all formfields that
    should be in this formfield.
    form: the form you want to split up in different formfields.
    formset: a name of your choosing to access the formfield.
    """
    try:
        # Ignore PyLintBear (W0612)
        _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)
