from django.conf import settings
from django.db.transaction import on_commit
from rest_framework import generics, status
from rest_framework.response import Response

from . import tasks, models, serializers


class ImageBaseView(generics.GenericAPIView):
    """Base Image view."""
    model = models.Image
    queryset = models.Image.objects.all()
    serializer_class = serializers.ImageSerializer


class ImageListCreateView(ImageBaseView, generics.ListCreateAPIView):
    """List/Create Image view."""


class ImageRetrieveDestroyView(ImageBaseView, generics.RetrieveDestroyAPIView):
    """Destroy view for model Image"""

    def delete(self, request, *args, **kwargs):
        """Override destroy view"""
        instance = self.get_object()
        if settings.USE_CELERY:
            on_commit(lambda: tasks.delete_image.delay(image_id=instance.id))
        else:
            on_commit(lambda: tasks.delete_image(image_id=instance.id))
        return Response(status=status.HTTP_204_NO_CONTENT)


class CropImageCreateView(ImageBaseView, generics.CreateAPIView):
    """Create crop image."""
    serializer_class = serializers.CropImageSerializer
