
from django.http import JsonResponse
from rest_framework.decorators import action, api_view
from django.views.decorators.csrf import csrf_exempt

from api.models import Paradero
from api.models import GtfsShape, GtfsTrips
from logging import error
from decouple import config

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.filter(vigente=True)
    for p in paraderos:

        id_comuna = None
        if p.id_comuna != None:
            id_comuna = p.id_comuna.id_comuna
        
        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': 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')

    """
    SELECT gs.shape_pt_lat, gs.shape_pt_lon, gs.shape_pt_sequence
    FROM gtfs_shape gs
    WHERE gs.id_shape in (
        SELECT DISTINCT id_shape
        FROM gtfs_trips gt
        WHERE gt.id_linea = '2990'
    )
    ORDER BY gs.id_shape, gs.sequence_coalesce
    """

    """
    # 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')
    """

    # Subconsulta interna
    subquery = GtfsTrips.objects.filter(id_linea=id_linea).values('id_shape').distinct()[:1]

    # Consulta principal
    query = GtfsShape.objects.filter(id_shape__in=subquery).order_by('id_shape', 'shape_pt_sequence')

    # Obtener los campos requeridos
    query = query.values('shape_pt_lat', 'shape_pt_lon', 'shape_pt_sequence')

    # Ejecutar la consulta
    resultados = query.all()

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

 
@action(detail=False, methods=['get'])
@api_view(['GET'])

def coordenadas(request):
    # Obtener las coordenadas iniciales desde las variables de entorno
    initial_lat = config('COORDINI_LAT', default=-36.8270)
    initial_lng = config('COORDINI_LNG', default=-73.0503)

    # Enviar las coordenadas iniciales como parte de la respuesta
    return JsonResponse({
        'initialLat': initial_lat,
        'initialLng': initial_lng, 
    })