from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from rest_framework.permissions import IsAdminUser, AllowAny
from rest_framework import generics
import os
from django.conf import settings
from django.http import FileResponse, Http404
from .serializers import PostImageCreateSerializer, PostImagesSerializer
from .models import PostImages # Make sure to import PostImages model

class ImageUploadView(APIView):
    parser_classes = (MultiPartParser, FormParser)
    permission_classes = (IsAdminUser,)

    def post(self, request, *args, **kwargs):
        """
        Accepts an image upload and processing parameters.
        Processes the image and saves it.
        """
        serializer = PostImageCreateSerializer(data=request.data)
        if serializer.is_valid():
            instance = serializer.save(user=request.user)
            # Return the details of the created object using the representation serializer
            return Response(serializer.to_representation(instance), status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class ImageDownloadView(APIView):
    """
    API endpoint to download a processed image by its slug.
    """
    def get(self, request, slug, *args, **kwargs):
        try:
            image_instance = PostImages.objects.get(slug=slug)
        except PostImages.DoesNotExist:
            raise Http404("Image not found.")

        file_path = os.path.join(settings.MEDIA_ROOT, image_instance.path)

        if not os.path.exists(file_path):
            raise Http404("File not found on server.")

        # Determine content type based on format
        content_type_map = {
            'png': 'image/png',
            'webp': 'image/webp',
            'jpg': 'image/jpeg',
            'avif': 'image/avif',
        }
        content_type = content_type_map.get(image_instance.format.lower(), 'application/octet-stream')
        
        # Prepare the filename for download
        filename = f"{image_instance.slug}.{image_instance.format.lower()}"

        response = FileResponse(open(file_path, 'rb'), content_type=content_type)
        response['Content-Disposition'] = f'attachment; filename="{filename}"'
        return response


class ImageListView(generics.ListAPIView):
    """List all images."""
    queryset = PostImages.objects.all().order_by('-created_at')
    serializer_class = PostImagesSerializer
    permission_classes = (AllowAny,)
