from django.http import Http404
from rest_framework import status
from rest_framework.response import Response
from  .models import Anime
from .serializers import AnimeSerializer
from rest_framework.decorators import api_view


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

    if request.method == 'GET':
        anime = Anime.objects.all()
        serializer = AnimeSerializer(anime, many=True)
        return Response(serializer.data)

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

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

    try:
        anime = Anime.objects.get(slug=slug)
    except Anime.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)
    except Anime.MultipleObjectsReturned:
        anime = Anime.objects.filter(slug=slug).first()

    if request.method == 'GET':
        serializer = AnimeSerializer(anime)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = AnimeSerializer(anime, 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':
        anime.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
