from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response

from ces_fall_rest_api.models.student import Student
from ces_fall_rest_api.models.student_in_section import StudentInSection
from ces_fall_rest_api.serializers.student_serializer import StudentSerializer
from ces_fall_rest_api.serializers.student_in_section_serializer import StudentInSectionSerializer
from ces_fall_rest_api.serializers.section_serializer import SectionSerializer
from ces_fall_rest_api.serializers.course_serializer import CourseSerializer
from rest_framework.permissions import IsAuthenticated


class StudentViewSet(viewsets.ModelViewSet):
    """A viewset to get the all the Student objects
    This class has a token authentication.
    It also has two action:
    1- available_survey
    2- enrolled_courses

    Args:
        viewsets (_type_): viewsets class

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

    # show what is the survey available by checking StudentInSection Evaluated == False
    @action(methods=['get'], detail=True)
    def available_survey(self, request, *args, **kwargs):
        student = self.get_object()

        sections_not_eval = StudentInSection.objects.filter(
            student=student, evaluated=False)

        response_builder = []
        for section in sections_not_eval:
            section_instance = section.section
            course_instance = section_instance.course
            section_ser = SectionSerializer(section_instance)
            course_ser = CourseSerializer(course_instance)
            combined_ser = section_ser.data
            combined_ser['course'] = course_ser.data
            response_builder.append(combined_ser)

        return Response(response_builder)

    # Check the enrolled courses of the student
    @action(methods=['get'], detail=True)
    def enrolled_courses(self, request, *args, **kwargs):
        student = self.get_object()

        sections_query_set = StudentInSection.objects.filter(student=student)
        serialized_sections = StudentInSectionSerializer(
            sections_query_set, many=True)

        return Response(serialized_sections.data)
