from core.models import Material, Quiz, SubjectRound, User, Meeting
from django.http import Http404
from rest_framework import serializers, status, permissions
from core.serializers.quiz_serializer import QuizSerializerCalender
from ..pagination import CustomResultsSetPagination
from rest_framework.response import Response
from rest_framework.views import APIView
from core.serializers.calender_serializer import CalenderSerializer
from core.serializers.subject_serializer import SubjectRoundSerializer
from core.serializers.meeting_serializer import MeetingSerializer
from django.utils import timezone

class CalenderView(APIView):
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = CustomResultsSetPagination
    serializer_class = CalenderSerializer

    def get_object(self, id):
        try:
            return CalenderSerializer.objects.get(pk=id)
        except CalenderSerializer.DoesNotExist:
            raise Http404

    def filter_events(self, user_, date=None, month=None, year=None):
        if date:
            return SubjectRound.objects.filter(students=user_, start_date__date=date)
        elif month:
            return SubjectRound.objects.filter(
                students=user_,
                start_date__month=month,
                start_date__year=year
            )
        return SubjectRound.objects.none()

    def filter_meetings(self, events, date=None, month=None, year=None):
        if date:
            return Meeting.objects.filter(date__date=date, subject_round__in=events)
        elif month:
            return Meeting.objects.filter(
                date__month=month,
                date__year=year,
                subject_round__in=events
            )
        return Meeting.objects.none()

    def filter_quizzes(self, events, date=None, month=None, year=None):
        if date:
            return Quiz.objects.filter(start_date__date=date, subject_round__in=events)
        elif month:
            return Quiz.objects.filter(
                start_date__month=month,
                start_date__year=year,
                subject_round__in=events
            )
        return Quiz.objects.none()

    def get(self, request, id=None):
        date_ = request.GET.get("date")
        month = request.GET.get("month")
        year = request.GET.get("year", timezone.now().date().year)
        user_ = request.user

        if not date_ and not month:
            return Response("Send month or date", status=status.HTTP_400_BAD_REQUEST)

        # Determine events based on user type and filters
        if user_.user_type == User.student:
            events = self.filter_events(user_, date_, month, year)
        elif user_.user_type == User.tutor:
            events = SubjectRound.objects.filter(tutor=user_, start_date__date=date_) if date_ else \
                     SubjectRound.objects.filter(tutor=user_, start_date__month=month, start_date__year=year) if month else \
                     SubjectRound.objects.none()
        else:
            events = self.filter_events(None, date_, month)

        meetings = self.filter_meetings(events, date_, month, year)
        quizzes = self.filter_quizzes(events, date_, month, year)

        if id:
            events = events.filter(course_round__pk=id)
            meetings = meetings.filter(subject_round__course_round__pk=id)
            quizzes = quizzes.filter(subject_round__course_round__pk=id)

        # Serialize the data
        response_data = {
            "subject_rounds": SubjectRoundSerializer(events, many=True).data,
            "meeting": MeetingSerializer(meetings, many=True).data,
            "quiz": QuizSerializerCalender(quizzes, many=True).data
        }

        return Response(response_data, status=status.HTTP_200_OK)

    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors)

    def put(self, request, id):
        course_round = self.get_object(id)
        serializer = self.serializer_class(course_round, partial=True, data=request.data)
        
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_202_ACCEPTED)
        
        return Response(serializer.errors)

    def patch(self, request, id):
        course_round = self.get_object(id)
        serializer = self.serializer_class(course_round, data=request.data, partial=True)

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_202_ACCEPTED)

        return Response(serializer.errors)

    def delete(self, request, id):
        course_round = self.get_object(id)
        course_round.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)