# -*- coding: utf-8 -*-
import json

from collections import OrderedDict
from rest_framework.utils import encoders

from events.forme.forms import widgets
from events.common_app.utils import timeit


class FormAsDictMixin(object):
    def as_json(self):
        return json.dumps(self.as_dict(), cls=encoders.JSONEncoder)

    @timeit
    def as_dict(self):
        form_dict = {
            'non_field_errors': self.non_field_errors(),
            'fields': self.get_fields_as_dicts()
        }
        return form_dict

    def get_fields_as_dicts(self):
        fields_dicts = OrderedDict()
        for field_name, field in self.fields.items():
            as_dict_field_class_name = field.widget.__class__.__name__
            widget_class = getattr(widgets, as_dict_field_class_name, widgets.AsDictWidget)
            fields_dicts[field_name] = widget_class(form=self, field_name=field_name, field=field).as_dict()
            fields_dicts[field_name]['name'] = field_name
        return fields_dicts
