from datetime import date, datetime, time

from django.db.models import Q
from django.views.generic import TemplateView

from sncfgtfs.models import Stop, StopTime, CalendarDate, Calendar


class GareView(TemplateView):
    template_name = "sncfgtfs/gare.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        stop = Stop.objects.get(name__iexact=kwargs["gare"], location_type=1)
        context['stop'] = stop
        next_departures = []

        now = datetime.now()
        if self.request.GET.get('date', None):
            query_date = date.fromisoformat(self.request.GET['date'])
        else:
            query_date = now.date()
        if self.request.GET.get('time', None):
            query_time = time.fromisoformat(self.request.GET['time'])
        else:
            query_time = now.time()
        context['query_date'] = query_date
        context['query_time'] = query_time

        qs = StopTime.objects.none()
        for child in Stop.objects.filter(name__iexact=kwargs["gare"], location_type=0).all():
            qs_child = StopTime.objects.filter(stop=child, pickup_type=0, departure_time__gte=query_time)
            qs_child = qs_child.filter(Q(trip__service_id__in=CalendarDate.objects.filter(
                                            date=query_date, exception_type=1).values_list('service_id'))
                                       | Q(trip__service_id__in=Calendar.objects.filter(
                                               start_date__lte=query_date,
                                               end_date__gte=query_date,
                                               **{f"{query_date:%A}".lower(): True})
                                           .filter(~Q(id__in=CalendarDate.objects.filter(
                                                        date=query_date, exception_type=2).values_list('service_id')))
                                           .values_list('id')))
            qs = qs.union(qs_child)
        next_departures += qs.order_by("departure_time")[:20].all()
        print(len(next_departures))
        context['next_departures'] = next_departures
        return context
