"""This module contains the apiv2 related views for the ``questionnaires`` app"""

from django.db.models import Prefetch

from rest_framework import filters, viewsets
from rest_framework.generics import mixins
from rest_framework.permissions import IsAuthenticated

from mtp.apps.api.mixins import ListLiveModelMixin
from mtp.apps.trainings.models import TrainingActivity

from ..models import (
    Answer,
    ChoicesAnswer,
    OpenAnswer,
    Question,
    Questionnaire,
)

from .serializers import (
    ChoicesAnswerSerializer,
    OpenAnswerSerializer,
    ReadAnswerSerializer,
)


class QuestionnaireViewSet(viewsets.GenericViewSet, mixins.RetrieveModelMixin):
    """ViewSet for the ``Questionnaire`` subclasses"""

    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        """Get the queryset to use, pre-fetching the ``Question`` and ``Choice``"""

        return TrainingActivity.objects.instance_of(Questionnaire).non_deleted().prefetch_related(
            Prefetch(
                'questions',
                queryset=Question.objects.non_deleted()
            )
        )

    def get_serializer_class(self):
        """Return the serializer class to use accordingly to the ``Questionnaire`` subclass"""

        return self.get_object().serializer_class


class OpenAnswerViewSet(viewsets.GenericViewSet, mixins.CreateModelMixin):
    """ViewSet for the ``OpenAnswer`` model"""

    permission_classes = [IsAuthenticated]
    serializer_class = OpenAnswerSerializer
    queryset = OpenAnswer.objects.non_deleted()


class ChoicesAnswerViewSet(viewsets.GenericViewSet, mixins.CreateModelMixin):
    """ViewSet for the ``ChoicesAnswer`` model"""

    permission_classes = [IsAuthenticated]
    serializer_class = ChoicesAnswerSerializer
    queryset = ChoicesAnswer.objects.non_deleted()


class ReadAnswerViewSet(ListLiveModelMixin, viewsets.GenericViewSet, mixins.ListModelMixin):
    """Read only ViewSet for the ``Answer`` model

    Notes
    -----
    This ViewSet inherit from ``ListLiveModelMixin`` and therefore must be called
    with a mandatory ``session`` GET parameter.

    """

    filter_backends = (filters.DjangoFilterBackend,)
    filter_fields = ('user',)
    permission_classes = [IsAuthenticated]
    serializer_class = ReadAnswerSerializer
    queryset = Answer.objects.non_deleted()
