from rest_framework import viewsets
from ces_fall_rest_api.models.outcome import Outcome
from ces_fall_rest_api.models.section import Section
from ces_fall_rest_api.serializers.outcome_serializer import OutcomeSerializer
from ces_fall_rest_api.serializers.section_serializer import SectionSerializer
from rest_framework.decorators import action
from rest_framework.response import Response
from ces_fall_rest_api.serializers.course_serializer import CourseSerializer
from rest_framework.permissions import IsAuthenticated


class SectionViewSet(viewsets.ModelViewSet):
    """A viewset to get the all the Section objects
    This class has a token authentication.
    It also has an action that retrive a specific section with the correct
    course name. 

    Args:
        viewsets (_type_): _description_

    Returns:
        _type_: _description_
    """
    queryset = Section.objects.all()
    serializer_class = SectionSerializer
    permission_classes = [IsAuthenticated]

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

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

    # A GET action to retrive a specific section with the correct course name
    @action(detail=False, methods=['get'], url_path='section_with_course')
    def section_with_course(self, request, section_id):
        section_instance = Section.objects.get(
            id=section_id)
        course_instance = section_instance.course

        sec_ser = self.get_serializer(section_instance)
        course_ser = CourseSerializer(course_instance)

        section_and_course_info = sec_ser.data
        section_and_course_info['course'] = course_ser.data

        course_outcomes = course_instance.outcomes
        outcomes_ser = OutcomeSerializer(course_outcomes, many=True)

        section_and_course_info['course']['outcomes'] = outcomes_ser.data
        return Response(section_and_course_info)
