
from django.http import JsonResponse
from rest_framework.decorators import action, api_view, schema
from django.views.decorators.csrf import csrf_exempt
from django.db.models import F, Subquery, Value
from django.db.models.functions import Coalesce

from ..models import Paradero, ParaderoImagen
from ..models import Linea, GtfsShape, GtfsTrips
from logging import error

google_api_key = 'AIzaSyDnFO9w_SsodjBuY5tOK8-kQJns_l5klQ4'
center = {'lat': -36.8077884, 'lng': -73.0775401}

@csrf_exempt
@action(detail=False, methods=['get'])
@api_view(['GET'])
def paraderos(request):
    zoom = 17
    marks = []

    paraderos = Paradero.objects.all()
    for p in paraderos:
        
        marks.append({
            'position': { 'lat': p.stop_lat, 'lng': p.stop_lon },
            'id_paradero': p.id_paradero,
            'title': 'Paradero #' + str(p.id_paradero),
            'location': p.stop_name,
            'id_comuna': p.id_comuna,
            'id_tipo_paradero': p.id_tipo_paradero,
        })

    return JsonResponse({
        'google_api_key': google_api_key,
        'zoom': zoom,
        'center': center,
        'marks': marks
    })


@csrf_exempt
@action(detail=False, methods=['get'])
@api_view(['GET'])
def rutas(request):
    id_linea = request.GET.get('id_linea')

    # Subquery para obtener los id_shape distintos de gtfs_trips
    subquery = GtfsTrips.objects.filter(id_linea = id_linea).values('id_shape').distinct()

    # Consulta principal con inner join y ordenamiento
    queryset = GtfsShape.objects.annotate(
        id_shape_subquery=Subquery(subquery),
        shape_pt_sequence_coalesce=Coalesce('shape_pt_sequence', Value(0))
    ).filter(id_shape=F('id_shape_subquery')).order_by('shape_pt_sequence_coalesce')

    result = queryset.values('shape_pt_lat', 'shape_pt_lon', 'shape_pt_sequence')

    return JsonResponse({
        'google_api_key': google_api_key,
        'positions': list(result)
    })