import json
import logging

from django.views.generic.base import View
from django.views.decorators.csrf import csrf_exempt
from django.http import Http404

from passerelle.utils import to_json
from .models import BaseQueue


logger = logging.getLogger(__name__)


class QueueView(View):
    STANDARD_ERRORS = (
            StandardError,
            ArithmeticError,
            BufferError,
            LookupError,
            EnvironmentError
    )

    def get_object(self):
        return BaseQueue.objects.get_slug(self.kwargs['slug'], self.request)

    def dispatch(self, request, *args, **kwargs):
        self.object = self.get_object()
        try:
            return super(QueueView, self).dispatch(request, *args, **kwargs)
        except QueueView.STANDARD_ERRORS:
            logger.exception('unexpected exception')
            raise
        except:
            raise

    def get_params(self):
        if self.object.parameters == '*':
            return self.request.GET.copy()
        else:
            params = {}
            for param in (self.object.parameters or ()):
                params[param] = self.request.GET.get(param)
            return params

    def get(self, request, *args, **kwargs):
        raise Exception('Method not allowed')

    def post(self, request, *args, **kwargs):
        data = json.loads(request.body)
        params = self.get_params()
        return self.object.queue(data, **kwargs)

queue = csrf_exempt(to_json('api')(QueueView.as_view()))
