import json

from django.views.generic.base import View
from django.views.generic.detail import SingleObjectMixin, DetailView
from django.views.generic.edit import UpdateView

from passerelle import utils
from passerelle.base.views import ResourceView

from .models import Pastell
from .forms import PastellTypeForm, PastellFieldsForm

class PostView(View, SingleObjectMixin):
    model = Pastell

    @utils.protected_api('can_post_document')
    def post(self, request, *args, **kwargs):
        data = json.loads(request.body)
        self.get_object().create_document(data)
        result = {'result': 'ok'}
        return utils.response_for_json(request, result)


class PastellDetailView(DetailView):
    model = Pastell

    def get_context_data(self, **kwargs):
        context = super(PastellDetailView, self).get_context_data(**kwargs)
        if self.object.document_type and self.object.document_fields:
            context['fields'] = []
            for field in self.object.get_document_fields().keys():
                if self.object.document_fields.get(field):
                    context['fields'].append({'key': field,
                        'value': self.object.document_fields.get(field)})
        return context


class PastellTypeView(UpdateView):
    model = Pastell
    form_class = PastellTypeForm
    template_name = 'passerelle/manage/service_form.html'


class PastellFieldsView(UpdateView):
    model = Pastell
    form_class = PastellFieldsForm
    template_name = 'passerelle/manage/service_form.html'


