import copy

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

register = template.Library()

def get_fieldset(parser, token):
    try:
        name, fields, as_, variable_name, from_, form = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError('bad arguments for %r'  % token.split_contents()[0])

    return FieldSetNode(fields.split(','), variable_name, form)

get_fieldset = register.tag(get_fieldset)


class FieldSetNode(template.Node):
    def __init__(self, fields, variable_name, form_variable):
        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, form.fields[key]) for key in self.fields if key in self.fields])
        context[self.variable_name] = new_form

        return u''

def phone(value):
    result = ""
    if len(value) == 10:
        for i in range(2, 11, 2):
            result += value[i-2:i] + " "
        result = result[:-1]
    else:
        result = value
    return result

register.filter('phone', phone)
