from rest_framework import generics, viewsets
from django_filters.rest_framework import DjangoFilterBackend
from django.http import HttpResponse, JsonResponse
from api.models import ParaderoImagen, Paradero
from api.serializers import ParaderoImagenSerializer

class ParaderoImagenListView(generics.ListAPIView, viewsets.ModelViewSet):
    queryset = ParaderoImagen.objects.all()
    serializer_class = ParaderoImagenSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['id_paradero', 'content_type']

    def retrieve(self, request, pk):
        data = ParaderoImagen.objects.filter(id_paradero_imagen = pk).first()
        response = HttpResponse(content_type=data.content_type)
        response['Content-Disposition'] = 'inline'
        response.write(data.imagen)
        return response

    def create(self, request, pk = None):
        imagen = request.FILES['imagen']
        id_paradero = request.data.get('id_paradero')
        content_type = imagen.content_type
        imagen_bytea = imagen.read()

        paradero = Paradero.objects.filter(id_paradero = id_paradero).first()

        paradero_imagen = ParaderoImagen(
            id_paradero = paradero,
            imagen = imagen_bytea,
            content_type = content_type
        )
        paradero_imagen.save()
        return JsonResponse({ 'ok': True })