from djangorestframework.views import View
from djangorestframework.permissions import IsAuthenticated
from djangorestframework.response import ErrorResponse
from djangorestframework import status as statuscodes
from django.shortcuts import get_object_or_404

from devilry_qualifiesforexam.pluginhelpers import create_sessionkey
from devilry.apps.core.models import Period
from devilry.utils.groups_groupedby_relatedstudent_and_assignment import GroupsGroupedByRelatedStudentAndAssignment
from devilry_subjectadmin.rest.auth import IsPeriodAdmin


class Preview(View):
    """
    Generate the data required to provide a preview for the qualified for exam wizard.

    # GET

    ## Parameters
    The following parameters are required:

    - ``periodid``: The ID of the period. Supplied as the last part of the URL-path.
      404 is returned unless the user is admin on this period.
    - ``pluginsessionid``: Forwarded from the first page of the wizard. It is an ID
      used to lookup the output from the plugin.

    ## Returns
    An object/dict with the following attributes:

    - ``pluginoutput``: The serialized output from the plugin.
    - ``perioddata``: All results for all students on the period.
    """
    permissions = (IsAuthenticated, IsPeriodAdmin)

    def get(self, request, id):
        pluginsessionid = self.request.GET.get('pluginsessionid', None)
        if not pluginsessionid:
            raise ErrorResponse(statuscodes.HTTP_400_BAD_REQUEST,
                {'detail': '``pluginsessionid`` is a required parameter'})
        period = get_object_or_404(Period, pk=id)
        previewdata = self.request.session[create_sessionkey(pluginsessionid)]
        grouper = GroupsGroupedByRelatedStudentAndAssignment(period)
        return {
            'perioddata': grouper.serialize(),
            'pluginoutput': previewdata.serialize()
        }
@@ -96,16 +96,71 @@
 ticated%0A
+from djangorestframework.resources import FormResource%0A
 from dja
@@ -206,16 +206,16 @@
 esponse%0A
-
 from dja
@@ -306,16 +306,41 @@
 t_or_404
+%0Afrom django import forms
 %0A%0Afrom d
@@ -621,16 +621,163 @@
 Admin%0A%0A%0A
+class PreviewForm(forms.Form):%0A    pluginsessionid = forms.CharField(required=True)%0A%0Aclass PreviewResource(FormResource):%0A    form = PreviewForm%0A%0A%0A
 class Pr
@@ -1493,16 +1493,47 @@
 odAdmin)
+%0A    resource = PreviewResource
 %0A%0A    de
@@ -1593,221 +1593,34 @@
 elf.
-request.GET.get('pluginsessionid', None)%0A        if not pluginsessionid:%0A            raise ErrorResponse(statuscodes.HTTP_400_BAD_REQUEST,%0A                %7B'detail': '%60%60pluginsessionid%60%60 is a required parameter'%7D)
+CONTENT%5B'pluginsessionid'%5D
 %0A   

Validate input.