from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.utils import OpenApiParameter, extend_schema

from django.utils.translation import gettext

from rest_framework.generics import get_object_or_404

from lms.core.views.pagination import LimitOffsetAllPagination
from lms.core.views.viewsets import LabModelViewSet
from lms.courses.models import Course
from lms.courses.permissions import CourseObjectPermission

from ..models import CourseFollower, CourseMailing, Mailing
from ..serializers import (
    CourseFollowerListLabSerializer, CourseMailingCreateLabSerializer, CourseMailingDetailLabSerializer,
    CourseMailingListLabSerializer, CourseMailingUpdateLabSerializer, MailingListLabSerializer,
)


class MailingLabViewSet(LabModelViewSet):
    serializer_class = MailingListLabSerializer
    queryset = Mailing.objects.all()
    pagination_class = None

    @extend_schema(
        summary=gettext("Список доступных рассылок")
    )
    def list(self, request, *args, **kwargs):
        return super().list(request, *args, **kwargs)


class CourseMailingLabViewSet(LabModelViewSet):
    serializer_class = CourseMailingListLabSerializer
    serializer_classes = {
        'retrieve': CourseMailingDetailLabSerializer,
        'create': CourseMailingCreateLabSerializer,
        'partial_update': CourseMailingUpdateLabSerializer,
        'update': CourseMailingUpdateLabSerializer,
    }
    queryset = CourseMailing.objects.all()
    permission_classes = LabModelViewSet.permission_classes + [CourseObjectPermission]
    pagination_class = None
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['is_active']

    def get_queryset(self):
        queryset = super().get_queryset()
        if self.action == 'list':
            course_id = self.kwargs['pk']
            filter_kwargs = {'course_id': course_id}
            queryset = queryset.filter(**filter_kwargs)

        return queryset

    def get_course(self, obj=None):
        if obj is not None:
            return obj.course

        queryset = Course.objects.all()
        if self.action == 'create':
            return get_object_or_404(queryset, pk=self.request.data.get('course_id'))
        if self.action == 'list':
            return get_object_or_404(queryset, pk=self.kwargs.get('pk'))

    @extend_schema(
        parameters=[
            OpenApiParameter(name='is_active', required=False, type=bool),
        ],
        summary=gettext("Список рассылок курса")
    )
    def list(self, request, *args, **kwargs):
        return super().list(request, *args, **kwargs)

    @extend_schema(
        responses={200: CourseMailingDetailLabSerializer},
        summary=gettext("Информация о рассылке курса")
    )
    def retrieve(self, request, *args, **kwargs):
        return super().retrieve(request, *args, **kwargs)

    @extend_schema(
        request=CourseMailingCreateLabSerializer,
        responses={201: CourseMailingDetailLabSerializer},
        summary=gettext("Добавление рассылки на курс"),
    )
    def create(self, request, *args, **kwargs):
        return super().create(request, *args, **kwargs)

    @extend_schema(
        request=CourseMailingUpdateLabSerializer,
        responses={200: CourseMailingDetailLabSerializer},
        summary=gettext("Обновление рассылки на курсе"),
    )
    def update(self, request, *args, **kwargs):
        return super().update(request, *args, **kwargs)

    @extend_schema(
        request=CourseMailingUpdateLabSerializer,
        responses={200: CourseMailingDetailLabSerializer},
        summary=gettext("Частичное обновление рассылки на курсе"),
    )
    def partial_update(self, request, *args, **kwargs):
        return super().partial_update(request, *args, **kwargs)

    @extend_schema(
        summary=gettext("Удаление рассылки из курса"),
    )
    def destroy(self, request, *args, **kwargs):
        return super().destroy(request, *args, **kwargs)


class CourseFollowerLabViewSet(LabModelViewSet):
    serializer_class = CourseFollowerListLabSerializer
    queryset = CourseFollower.objects.all()
    pagination_class = LimitOffsetAllPagination
    permission_classes = LabModelViewSet.permission_classes + [CourseObjectPermission]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['is_active']

    def get_queryset(self):
        queryset = super().get_queryset()
        if self.action == 'list':
            course_id = self.kwargs['pk']
            filter_kwargs = {'course_id': course_id}
            queryset = queryset.filter(**filter_kwargs)

        return queryset

    def get_course(self, obj=None):
        queryset = Course.objects.all()
        if self.action == 'list':
            return get_object_or_404(queryset, pk=self.kwargs.get('pk'))

    @extend_schema(
        parameters=[
            OpenApiParameter(name='is_active', required=False, type=bool),
        ],
        summary=gettext("Список подписчиков курса")
    )
    def list(self, request, *args, **kwargs):
        return super().list(request, *args, **kwargs)
