from datetime import date

from django.utils import timezone as tz
from django.views.generic import ListView

from ..models import Diffusion, Log, Page, StaticPage
from .base import BaseView


class HomeView(BaseView, ListView):
    template_name = "aircox/home.html"
    model = Diffusion
    attach_to_value = StaticPage.ATTACH_TO_HOME
    queryset = Diffusion.objects.on_air().select_related("episode")
    logs_count = 5
    publications_count = 5
    has_filters = False

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

    def get_logs(self, diffusions):
        today = date.today()
        logs = Log.objects.on_air().date(today).filter(track__isnull=False)
        # diffs = Diffusion.objects.on_air().date(today)
        return Log.merge_diffusions(logs, diffusions, self.logs_count)

    def get_next_diffs(self):
        now = tz.now()
        current_diff = Diffusion.objects.on_air().now(now).first()
        next_diffs = Diffusion.objects.on_air().after(now)
        if current_diff:
            diffs = [current_diff] + list(next_diffs.exclude(pk=current_diff.pk)[:2])
        else:
            diffs = next_diffs[:3]
        return diffs

    def get_last_publications(self):
        # note: with postgres db, possible to use distinct()
        qs = Page.objects.select_subclasses().published().order_by("-pub_date")
        parents = set()
        items = []
        for publication in qs:
            parent_id = publication.parent_id
            if parent_id is not None and parent_id in parents:
                continue
            items.append(publication)
            if len(items) == self.publications_count:
                break
        return items

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["logs"] = self.get_logs(context["object_list"])
        context["next_diffs"] = self.get_next_diffs()
        context["last_publications"] = self.get_last_publications()[:5]
        return context
