from rest_framework import viewsets
from ces_fall_rest_api.models.semester import Semester
from ces_fall_rest_api.models.student_in_section import StudentInSection
from ces_fall_rest_api.serializers.student_in_section_serializer import StudentInSectionSerializer
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.decorators import action
from ces_fall_rest_api.models.section import Section


class StudentInSectionViewSet(viewsets.ModelViewSet):
    """A viewset to get the all the StudentInSection objects
    This class has a token authentication.
    It also has an action that retrive the count of students that enrolled
    to a course and the count of the students that were not evaluated the course.

    Args:
        viewsets (_type_): viewsets class

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

    def get_object(self):
        lookup_args = ['student', 'section']

        if all(arg in self.kwargs for arg in lookup_args):
            return StudentInSection.objects.get(**self.kwargs)
        else:
            return super().get_object()

    @action(detail=False, methods=['get'], url_path='section_student_count')
    def section_student_count(self, request, reference, year, month, pk=None):
        section_instance = Section.objects.get(
            reference=reference, semester=Semester.objects.get(year=year, month=month))
        student_enrolled_count = StudentInSection.objects.filter(
            section=section_instance).count()
        student_NotEvaluated_count = StudentInSection.objects.filter(
            section=section_instance, evaluated=False).count()

        data = {
            'student_enrolled_count': student_enrolled_count,
            'student_not_evaluated_count': student_NotEvaluated_count
        }

        return Response(data)

    @action(detail=False, methods=['get'], url_path='student_evaluated')
    def student_evaluated(self, request, student, section):
        student_in_section_instance = StudentInSection.objects.get(
            student=student, section=section)

        serializer = self.get_serializer(student_in_section_instance)

        section_and_course_info = serializer.data

        return Response(section_and_course_info)
