from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser

from .models import Pharmacy
from .serializers import PharmacySerializer


@csrf_exempt
def pharmacies_list(request):

    if request.method == 'GET':
        pharmacies = Pharmacy.objects.all()
        serializer = PharmacySerializer(pharmacies, many=True)
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = PharmacySerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)


@csrf_exempt
def pharmacy_detail(request, pk):
    try:
        pharmacy = Pharmacy.objects.get(pk=pk)
    except Pharmacy.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = PharmacySerializer(pharmacy)
        return JsonResponse(serializer.data)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        serializer = PharmacySerializer(pharmacy, data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data)
        return JsonResponse(serializer.errors, status=400)

    elif request.method == 'DELETE':
        pharmacy.delete()
        return HttpResponse(status=204)
