from django.http.response import JsonResponse
from rest_framework.views import APIView
from rest_framework import status
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from django.views.decorators.csrf import ensure_csrf_cookie, csrf_protect
from django.utils.decorators import method_decorator
from Subscriptions.serializers import AbsenceManagementSerializer
from Subscriptions.models import AbsenceManagement
from N3wtSchool.bdd import delete_object

@method_decorator(csrf_protect, name='dispatch')
@method_decorator(ensure_csrf_cookie, name='dispatch')
class AbsenceManagementListCreateView(APIView):
    def get(self, request):
        absences = AbsenceManagement.objects.all()
        serializer = AbsenceManagementSerializer(absences, many=True)
        return JsonResponse(serializer.data, safe=False, status=status.HTTP_200_OK)

    def post(self, request):
        serializer = AbsenceManagementSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, safe=False, status=status.HTTP_201_CREATED)
        return JsonResponse(serializer.errors, safe=False, status=status.HTTP_400_BAD_REQUEST)

@method_decorator(csrf_protect, name='dispatch')
@method_decorator(ensure_csrf_cookie, name='dispatch')
class AbsenceManagementDetailView(APIView):
    def get(self, request, id):
        try:
            absence = AbsenceManagement.objects.get(id=id)
            serializer = AbsenceManagementSerializer(absence)
            return JsonResponse(serializer.data, safe=False, status=status.HTTP_200_OK)
        except AbsenceManagement.DoesNotExist:
            return JsonResponse({"error": "Absence not found"}, safe=False, status=status.HTTP_404_NOT_FOUND)

    def put(self, request, id):
        try:
            absence = AbsenceManagement.objects.get(id=id)
            serializer = AbsenceManagementSerializer(absence, data=request.data)
            if serializer.is_valid():
                serializer.save()
                return JsonResponse(serializer.data, safe=False, status=status.HTTP_200_OK)
            return JsonResponse(serializer.errors, safe=False, status=status.HTTP_400_BAD_REQUEST)
        except AbsenceManagement.DoesNotExist:
            return JsonResponse({"error": "Absence not found"}, safe=False, status=status.HTTP_404_NOT_FOUND)

    def delete(self, request, id):
        return delete_object(AbsenceManagement, id)