from django.http import JsonResponse
from rest_framework import viewsets
from rest_framework.decorators import action
from api.serializers import ParaderoSerializer
from api.models import Paradero
import logging

class ParaderoViewSet(viewsets.ModelViewSet):
    queryset = Paradero.objects.all()
    serializer_class = ParaderoSerializer


    @action(detail=False, methods=['get'])
    def count(self, request, pk=None):

        queryset = Paradero.objects.all()

        if 'vigente' in request.GET and request.GET['vigente'] == '1':
            queryset = queryset.filter(vigente=True)

        if 'vigente' in request.GET and request.GET['vigente'] == '0':
            queryset = queryset.filter(vigente=False)

        if 'id_comuna' in request.GET:
            pass
        
        return JsonResponse({ 'count': queryset.count() })


def info_public(request, pk):

    if hasattr(request.META,'HTTP_REFERER'):
        referer = request.META['HTTP_REFERER']
    else:
        protocol = request.scheme
        host = request.META['HTTP_HOST']
        port = request.META['SERVER_PORT']
        referer = f'{protocol}://{host}:{port}'

    return JsonResponse({
        'url_public': f'{referer}/public/infoStop?codigoParadero={pk}'
    })