import datetime


from django.urls import reverse

from aircox.models import Diffusion, Log, StaticPage
from aircox.views.diffusion import TimeTableView as AircoxTimeTableView
from aircox.views.diffusion import BaseDiffusionListView
from aircox.views.mixins import GetDateMixin
from aircox.views.page import attach

__all__ = ("HomeTimeTableView", "TimeTableView")


class HomeTimeTableView(AircoxTimeTableView):
    template_name = "aircox/home.html"


@attach
class TimeTableView(GetDateMixin, BaseDiffusionListView):
    model = Diffusion
    redirect_date_url = "timetable-list"
    attach_to_value = StaticPage.Target.TIMETABLE
    template_name = "aircox/timetable_list.html"

    def get_date(self, param="date"):
        date = super().get_date(param)
        return date if date is not None else datetime.date.today()

    def get_logs(self, date):
        return Log.objects.on_air().date(self.date).filter(track__isnull=False)

    def get_queryset(self):
        return super().get_queryset().date(self.date)

    @classmethod
    def get_secondary_nav(cls):
        date = datetime.date.today()
        start = date - datetime.timedelta(days=3)
        dates = [start + datetime.timedelta(days=i) for i in range(0, 7)]
        return tuple((date.strftime("%A %d"), reverse("timetable-list", kwargs={"date": date})) for date in dates)

    def get_context_data(self, object_list=None, **kwargs):
        start = self.date - datetime.timedelta(days=3)
        dates = [start + datetime.timedelta(days=i) for i in range(0, 7)]

        if object_list is None:
            logs = self.get_logs(self.date)
            object_list = Log.merge_diffusions(logs, self.object_list, group_logs=True)
        object_list = list(reversed(object_list))
        return super().get_context_data(date=self.date, dates=dates, object_list=object_list, **kwargs)
