
from rest_framework import viewsets
from rest_framework.decorators import action
from django_filters.rest_framework import DjangoFilterBackend
from django.core.files.storage import FileSystemStorage
from django.http import FileResponse, HttpResponse
from api import models , serializers
from decouple import config
import os
import logging

class GtfsArchivoViewSet(viewsets.ModelViewSet):
    queryset = models.GtfsArchivo.objects.all()
    serializer_class = serializers.GtfsArchivoSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['id_gtfs', 'id_red', 'archivo','valid_from','created','usuario','vigente','status']
    

    def create(self, request, *args, **kwargs):
        fs = FileSystemStorage(location = config('GTFS_UPLOADS','/tmp'))

        fileUp = fs.save(request.data['archivo'], request.data['binario'])
        request.data['ruta_archivo'] = fileUp

        return super().create(request, *args, **kwargs)

    @action(detail=False, methods=['get'])
    def download(self, request, *args, **kwargs):
        try:
            id = request.GET['id']
            registro = models.GtfsArchivo.objects.filter(id_gtfs = id).first()

            folder = config('GTFS_UPLOADS','/tmp')
            file_location = os.path.join(folder, registro.ruta_archivo)

            archivo = open(file_location, 'rb')
            response = FileResponse(archivo)
            response['Access-Control-Expose-Headers'] = 'Content-Disposition'
            response['Content-Type'] = 'application/zip' 
            response['Content-Disposition'] = f'attachment; filename="{registro.archivo}"' 
            return response
        except Exception as err:
            logging.error({ 'error': err })
            return HttpResponse('Error al descargar archivo', status=500)