from django.http import JsonResponse
from rest_framework import status
from rest_framework.response import Response

from  .models import Manga
from .serializers import MangaSerializer
from rest_framework.decorators import api_view


@api_view(['GET', 'POST'])
def manga_crud(request, format=None):

    if request.method == 'GET':
        manga = Manga.objects.all()
        serializer = MangaSerializer(manga, many=True)
        return Response(serializer.data)

    if request.method == 'POST':
        serializer = MangaSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)

@api_view(['GET', 'PUT', 'DELETE'])
def manga_detail(request, slug, format=None):

    try:
        manga = Manga.objects.get(slug=slug)
    except Manga.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = MangaSerializer(manga)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = MangaSerializer(manga, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        manga.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)