import datetime

from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.shortcuts import get_object_or_404
from django.db.transaction import atomic
from django.contrib.auth import authenticate, login, logout

from rest_framework import viewsets, routers, generics
from rest_framework.decorators import link
from rest_framework import status
from rest_framework.response import Response
from rest_framework.exceptions import MethodNotAllowed, APIException
from rest_framework.reverse import reverse
from rest_framework.permissions import IsAuthenticated

import snotes20.models as models
import snotes20.serializers as serializers
import snotes20.views as views


router = routers.DefaultRouter()

router.register(r'auth', views.AuthViewSet, base_name='auth')
router.register(r'users', views.UserViewSet, base_name='users')
router.register(r'soonepisodes', views.SoonEpisodeViewSet, base_name='sonnepisode')
router.register(r'documents', views.DocumentViewSet, base_name='document')


class UnprocessableEntity(APIException):
    status_code = 422

    def __init__(self, detail):
        self.detail = detail


class DocumentByEpisodeViewSet(viewsets.ViewSet):
    def list(self, request):
        return 0

    def create(self, request, episode=None):
        doc = models.Document()
        ep = get_object_or_404(models.Episode.objects.filter(id=episode))

        if ep.document_id:
            raise UnprocessableEntity('this episode has a document')

        if 'name' not in request.DATA:
            raise UnprocessableEntity('no name supplied')

        name = request.DATA['name']

        if models.Document.objects.filter(name=name).exists():
            raise UnprocessableEntity('name taken')

        doc.name = name
        ep.document = doc

        with atomic():
            doc.save()
            ep.save()

        return Response(
            headers={'Location': reverse('document-detail', request=request, args=[name])},
            status=status.HTTP_201_CREATED
        )

    def retrieve(self, request, pk=None, episode=None):
        doc = get_object_or_404(models.Document.objects.all().filter(episode=episode))
        return serializers.DocumentSerializer(doc)

    def update(self, request, pk=None):
        pass

    def partial_update(self, request, pk=None):
        pass

    def destroy(self, request, pk=None):
        pass


doc_by_ep_url = url('^documents/by-episode/(?P<episode>.+)/$',
                    DocumentByEpisodeViewSet.as_view({
                        'get': 'retrieve',
                        'post': 'create',
                    }))


urlpatterns = patterns('',
    url(r'^', include(router.urls)),
    doc_by_ep_url,
    url(r'^admin/', include(admin.site.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
)

@@ -1,21 +1,4 @@
-import datetime%0A%0A
 from
@@ -82,577 +82,44 @@
 min%0A
-from django.shortcuts import get_object_or_404%0Afrom django.db.transaction import atomic%0Afrom django.contrib.auth import authenticate, login, logout%0A%0Afrom rest_framework import viewsets, routers, generics%0Afrom rest_framework.decorators import link%0Afrom rest_framework import status%0Afrom rest_framework.response import Response%0Afrom rest_framework.exceptions import MethodNotAllowed, APIException%0Afrom rest_framework.reverse import reverse%0Afrom rest_framework.permissions import IsAuthenticated%0A%0Aimport snotes20.models as models%0Aimport snotes20.serializers as serializers
+%0Afrom rest_framework import routers%0A
 %0Aimp
@@ -147,17 +147,16 @@
  views%0A%0A
-%0A
 router =
@@ -471,1620 +471,8 @@
 ')%0A%0A
-%0Aclass UnprocessableEntity(APIException):%0A    status_code = 422%0A%0A    def __init__(self, detail):%0A        self.detail = detail%0A%0A%0Aclass DocumentByEpisodeViewSet(viewsets.ViewSet):%0A    def list(self, request):%0A        return 0%0A%0A    def create(self, request, episode=None):%0A        doc = models.Document()%0A        ep = get_object_or_404(models.Episode.objects.filter(id=episode))%0A%0A        if ep.document_id:%0A            raise UnprocessableEntity('this episode has a document')%0A%0A        if 'name' not in request.DATA:%0A            raise UnprocessableEntity('no name supplied')%0A%0A        name = request.DATA%5B'name'%5D%0A%0A        if models.Document.objects.filter(name=name).exists():%0A            raise UnprocessableEntity('name taken')%0A%0A        doc.name = name%0A        ep.document = doc%0A%0A        with atomic():%0A            doc.save()%0A            ep.save()%0A%0A        return Response(%0A            headers=%7B'Location': reverse('document-detail', request=request, args=%5Bname%5D)%7D,%0A            status=status.HTTP_201_CREATED%0A        )%0A%0A    def retrieve(self, request, pk=None, episode=None):%0A        doc = get_object_or_404(models.Document.objects.all().filter(episode=episode))%0A        return serializers.DocumentSerializer(doc)%0A%0A    def update(self, request, pk=None):%0A        pass%0A%0A    def partial_update(self, request, pk=None):%0A        pass%0A%0A    def destroy(self, request, pk=None):%0A        pass%0A%0A%0Adoc_by_ep_url = url('%5Edocuments/by-episode/(?P%3Cepisode%3E.+)/$',%0A                    DocumentByEpisodeViewSet.as_view(%7B%0A                        'get': 'retrieve',%0A                        'post': 'create',%0A                    %7D))%0A%0A%0A
 urlp
@@ -535,27 +535,8 @@
 )),%0A
-    doc_by_ep_url,%0A
     

remove DocumentByEpisodeViewSet as it needs to be rewritten anyway