from django.http.response import JsonResponse
from django.views.decorators.csrf import ensure_csrf_cookie, csrf_protect
from django.utils.decorators import method_decorator
from rest_framework.parsers import JSONParser
from rest_framework.views import APIView
from rest_framework import status
from .models import Establishment
from .serializers import EstablishmentSerializer
from N3wtSchool.bdd import delete_object, getAllObjects, getObject

@method_decorator(csrf_protect, name='dispatch')
@method_decorator(ensure_csrf_cookie, name='dispatch')
class EstablishmentListCreateView(APIView):
    def get(self, request):
        establishments = getAllObjects(Establishment)
        establishments_serializer = EstablishmentSerializer(establishments, many=True)
        return JsonResponse(establishments_serializer.data, safe=False, status=status.HTTP_200_OK)

    def post(self, request):
        establishment_data = JSONParser().parse(request)
        establishment_serializer = EstablishmentSerializer(data=establishment_data)
        if establishment_serializer.is_valid():
            establishment_serializer.save()
            return JsonResponse(establishment_serializer.data, safe=False, status=status.HTTP_201_CREATED)
        return JsonResponse(establishment_serializer.errors, safe=False, status=status.HTTP_400_BAD_REQUEST)

@method_decorator(csrf_protect, name='dispatch')
@method_decorator(ensure_csrf_cookie, name='dispatch')
class EstablishmentDetailView(APIView):
    def get(self, request, id=None):
        try:
            establishment = Establishment.objects.get(id=id)
            establishment_serializer = EstablishmentSerializer(establishment)
            return JsonResponse(establishment_serializer.data, safe=False)
        except Establishment.DoesNotExist:
            return JsonResponse({'error': 'No object found'}, status=status.HTTP_404_NOT_FOUND)

    def put(self, request, id):
        establishment_data = JSONParser().parse(request)
        try:
            establishment = Establishment.objects.get(id=id)
        except Establishment.DoesNotExist:
            return JsonResponse({'error': 'No object found'}, status=status.HTTP_404_NOT_FOUND)
        establishment_serializer = EstablishmentSerializer(establishment, data=establishment_data, partial=True)
        if establishment_serializer.is_valid():
            establishment_serializer.save()
            return JsonResponse(establishment_serializer.data, safe=False)
        return JsonResponse(establishment_serializer.errors, safe=False, status=status.HTTP_400_BAD_REQUEST)

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