from rest_framework import viewsets
from ces_fall_rest_api.models.outcome import Outcome
from ces_fall_rest_api.serializers.outcome_serializer import OutcomeSerializer
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import action
from rest_framework.response import Response


class OutcomeViewSet(viewsets.ModelViewSet):
    """A viewset to get the all the Outcome objects
    This class has a token authentication.
    It also has an action to retrive the outcome by course.id.

    Args:
        viewsets (_type_): viewsets class

    Returns:
        _type_: Response in JSON format
    """
    queryset = Outcome.objects.all()
    serializer_class = OutcomeSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        lookup_args = ['heading', 'year', 'month']

        if all(arg in self.kwargs for arg in lookup_args):
            heading = self.kwargs['heading'].strip()
            return Outcome.objects.get(heading=heading, semester__year=self.kwargs['year'], semester__month=self.kwargs['month'])
        else:
            return super().get_object()

    # A GET action to retrive the outcome by course.id
    @action(detail=False, methods=['get'], url_path='course_outcomes')
    def course_outcomes(self, request, id):
        queryset = Outcome.objects.filter(course__id=id)
        serializer = OutcomeSerializer(queryset, many=True)

        return Response(serializer.data)
