"""
Views
=====
Views reacting to Http Requests by interfacing between backend and frontend.

Functions
---------
index(request)
    Home page
"""
from django.shortcuts import render
from django.http import HttpResponse, HttpRequest
from .models import *
from .forms import *
import json
from datetime import datetime

def print_r(r, s):
    if not len(r):
        print(s)
    return r

def get_timetable(r, trips, stop_sequences):
    timetable = {"stop_sequence": stop_sequences[r.route_id]}
    sts = {}
    for stop in stop_sequences[r.route_id]:
        times = []
        for t in trips[r.route_id]:
            for st in StopTime.objects.filter(trip_id=t.trip_id):
                times.append(st.departure_time.strftime("%H:%M")) 
        sts[stop] = times
    timetable["stop_times"] =  sts
    return timetable


def index(request):
    stops = [{name: getattr(s, name) for name in ['stop_id', 'stop_name', 'stop_lat', 'stop_lon']} for s in Stop.objects.all()]
    route_name = lambda r : r.route_short_name if r.route_short_name else r.route_long_name
    routes = [{"route_id": r.route_id, "route_type": r.route_type, "route_name": route_name(r), "agency_id": r.agency_id.agency_id} for r in Route.objects.all()]
    trips = {r["route_id"]: [t for t in Trip.objects.filter(route_id_id=r["route_id"])] for r in routes}
    stop_sequences = {}
    for r in routes:
        seq = []
        t = trips[r["route_id"]]
        for s in StopTime.objects.filter(trip_id_id__exact=t[0].trip_id):
            seq.append(s)
        stop_sequences[r["route_id"]] = [s.stop_id.stop_id for s in sorted(seq, key=lambda st : st.stop_sequence)]
    timetable = {}
    if request.GET.get("timetable"):
        try:
            r = Route.objects.get(route_id=request.GET.get("timetable"))
            timetable = get_timetable(r, trips, stop_sequences)
        except Route.DoesNotExist:
            print(f"Invalid request for Route with id {request.GET['timetable']}")
    context = {"stops": json.dumps(stops), "routes": json.dumps(routes), "timetable": json.dumps(timetable)}
    return render(request,"map.html", context)

