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, Dispositivo
from decouple import config
import logging
from django.db.models import Count

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() })
        
    @action(detail=False, methods=['get'], url_path='count_by_comuna')
    def count_by_comuna(self, request, pk=None):
            # Solo paraderos vigentes
            queryset = Paradero.objects.filter(vigente=True)

            # Conteo agrupado por comuna
            count_by_comuna = queryset.values('id_comuna__nombre_comuna').annotate(total=Count('id_paradero')).order_by('id_comuna')

            return JsonResponse({'count_by_comuna': list(count_by_comuna)})
        
    @action(detail=False, methods=['get'], url_path='info-public/(?P<pk>\S+)')
    def info_public(self, request, pk=None):
        if 'HTTP_REFERER' in request.META:
            referer = request.META['HTTP_REFERER']
        else:
            protocol = request.scheme
            host = request.META['HTTP_HOST']
            port = request.META['SERVER_PORT']
            referer = f'{protocol}://{host}'

        record = Dispositivo.objects \
            .filter(id_tipo_dispositivo__descripcion='CODIGO QR', id_paradero=pk) \
            .first()

        url = None
        if record != None:
            base_url = config('URL_PARADERO', 'http://localhost/')
            url = f'{base_url}{record.id_dispositivo}'


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