from drf_spectacular.utils import extend_schema

from django.contrib.auth import get_user_model
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.utils.translation import gettext

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

from lms.core.views.viewsets import APIModelViewSet
from lms.courses.permissions import IsCourseStudent
from lms.courses.views.api import CourseModuleBaseViewSet

from ..models import Assignment, AssignmentStudentResult, CourseStudent
from ..serializers import AssignmentDetailSerializer, AssignmentStudentResultDetailSerializer

User = get_user_model()


class AssignmentViewSet(CourseModuleBaseViewSet):
    """
    Модуль задания
    """
    serializer_class = AssignmentDetailSerializer
    queryset = Assignment.objects.active()

    @extend_schema(
        summary=gettext("Информация о задании"),
    )
    def retrieve(self, request, *args, **kwargs):
        return super().retrieve(request, *args, **kwargs)


class AssignmentStudentResultViewSet(APIModelViewSet):
    """
    Результат пользователя по модулю задания
    """
    permission_classes = [IsCourseStudent, ]
    serializer_class = AssignmentStudentResultDetailSerializer
    queryset = AssignmentStudentResult.objects.all()
    _cached_assignment = None
    lookup_url_kwarg = 'pk'
    lookup_field = 'assignment_id'

    def get_queryset(self):
        queryset = super().get_queryset()
        user = getattr(self.request, 'user', None)
        if user and isinstance(user, User):
            return queryset.filter(
                student__user=user,
                student__status=CourseStudent.StatusChoices.ACTIVE,
            )
        return queryset.none()

    def get_assignment(self):
        if not self._cached_assignment:
            self._cached_assignment = get_object_or_404(
                Assignment.objects.active().select_related('course'),
                pk=self.kwargs.get('pk'),
            )
        return self._cached_assignment

    def get_course(self):
        return self.get_assignment().course

    @extend_schema(
        summary=gettext("Информация о результате задания"),
    )
    def retrieve(self, request, *args, **kwargs):
        # ищем активного студента, чтобы отличать ситуации: когда его нет и когда он есть, а нет AssignmentStudentResult
        get_object_or_404(
            CourseStudent.objects.active(),
            user=self.request.user, course=self.get_course()
        )
        try:
            result = self.get_object()
        except Http404:
            result = {'is_completed': False}
        serializer = self.get_serializer(result)
        return Response(serializer.data)

    @extend_schema(
        request=None,
        responses={204: None},
        summary=gettext("Отметить задание как выполненное")
    )
    @action(detail=True, methods='post')
    def set_completed(self, request, *args, **kwargs):
        student = get_object_or_404(
            CourseStudent.objects.active(),
            user=self.request.user, course=self.get_course()
        )
        self.get_assignment().complete(student=student)
        return Response(status=status.HTTP_204_NO_CONTENT)

    @extend_schema(
        request=None,
        responses={204: None},
        summary=gettext("Отметить задание как невыполненное")
    )
    @action(detail=True, methods='post')
    def set_incomplete(self, request, *args, **kwargs):
        student = get_object_or_404(
            CourseStudent.objects.active(),
            user=self.request.user, course=self.get_course()
        )
        self.get_assignment().update_completed_field(student=student, value=False)
        return Response(status=status.HTTP_204_NO_CONTENT)
