from django.conf import settings
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.generic import View
from django.views.generic.edit import FormMixin
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt

from rapidsms.log.mixin import LoggerMixin

from threadless_router.base import incoming
from threadless_router.backends.http.forms import HttpForm


class BaseHttpBackendView(FormMixin, LoggerMixin, View):

    conf = {}

    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(BaseHttpBackendView, self).dispatch(*args, **kwargs)

    def post(self, request, *args, **kwargs):
        self.backend_name = kwargs.get('backend_name')
        if not self.conf:
            self.conf = settings.INSTALLED_BACKENDS[self.backend_name]
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        if form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

    def form_valid(self, form):
        self.debug('form is valid')
        incoming(self.backend_name, **form.get_incoming_data())
        return HttpResponse('OK')

    def form_invalid(self, form):
        self.debug('form failed to validate')
        errors = dict((k, v[0]) for k, v in form.errors.items())
        self.debug(unicode(errors))
        return HttpResponseBadRequest('form failed to validate')


class SimpleHttpBackendView(BaseHttpBackendView):

    form_class = HttpForm

    def get_form_kwargs(self):
        kwargs = super(SimpleHttpBackendView, self).get_form_kwargs()
        kwargs.update({
            'identity': self.conf.get('incoming_identity', 'identity'),
            'text': self.conf.get('incoming_text', 'text'),
        })
        return kwargs

@@ -91,46 +91,8 @@
 est%0A
-from django.views.generic import View%0A
 from
@@ -134,16 +134,33 @@
 ormMixin
+, ProcessFormView
 %0Afrom dj
@@ -458,24 +458,35 @@
 rMixin, 
+ProcessForm
 View):%0A%0A
     conf
@@ -473,24 +473,57 @@
 FormView):%0A%0A
+    http_method_names = %5B'post'%5D%0A
     conf = %7B
@@ -525,10 +525,12 @@
 f = 
-%7B%7D
+None
 %0A%0A  
@@ -794,12 +794,8 @@
  if 
-not 
 self
@@ -799,16 +799,24 @@
 elf.conf
+ is None
 :%0A      
@@ -892,208 +892,77 @@
     
-form_class = self.get_form_class()%0A        form = self.get_form(form_class)%0A        if form.is_valid():%0A            return self.form_valid(form)%0A        else:%0A            return self.form_invalid(form
+return super(BaseHttpBackendView, self).post(request, *args, **kwargs
 )%0A%0A 

modify backends.http to use ProcessFormView and only accept HTTP POSTs