import json

from django.core.urlresolvers import reverse
from django.views.generic.edit import CreateView, UpdateView, DeleteView, View
from django.views.generic.detail import SingleObjectMixin
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt

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

from .models import ChoositSMSGateway, ChoositRegisterGateway
from .forms import ChoositRegisterGatewayForm


class ChoositDetailView(ResourceView):
    model = ChoositSMSGateway
    template_name = 'passerelle/manage/messages_service_view.html'


class ChoositRegisterDetailView(ResourceView):
    model = ChoositRegisterGateway
    template_name = 'choosit/choosit_register_detail.html'


class ChoositRegisterCreateView(CreateView):
    model = ChoositRegisterGateway
    template_name = 'passerelle/manage/service_form.html'
    form_class = ChoositRegisterGatewayForm


class ChoositRegisterUpdateView(UpdateView):
    model = ChoositRegisterGateway
    template_name = 'passerelle/manage/service_form.html'
    form_class = ChoositRegisterGatewayForm


class ChoositRegisterDeleteView(DeleteView):
    model = ChoositRegisterGateway
    template_name = 'passerelle/manage/service_confirm_delete.html'

    def get_success_url(self):
        return reverse('manage-home')


class ChoositRegisterView(View, SingleObjectMixin):
    model = ChoositRegisterGateway

    @method_decorator(csrf_exempt)
    @utils.protected_api('can_post_request')
    def dispatch(self, request, *args, **kwargs):
        return super(ChoositRegisterView, self).dispatch(request, *args, **kwargs)

    @utils.to_json('api')
    @method_decorator(csrf_exempt)
    def get(self, request, *args, **kwargs):
        user = request.GET.get('user')
        assert user, 'missing user parameter'
        return self.get_object().get_list(user)

    @utils.to_json('api')
    def post(self, request, *args, **kwargs):
        user = request.GET.get('user')
        assert user, 'missing user parameter'
        data = json.loads(request.body)
        assert isinstance(data, list), 'body must be a JSON list'
        return self.get_object().post(user, data)
