from datetime import date, datetime, timedelta

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

from ..models import Diffusion, Episode, Log, Page, StaticPage
from .base import BaseView
from .mixins import AttachedToMixin


class HomeView(AttachedToMixin, BaseView, ListView):
    template_name = "aircox/home.html"
    attach_to_value = StaticPage.Target.HOME
    model = Diffusion
    queryset = Diffusion.objects.on_air().select_related("episode").order_by("-start")

    publications_queryset = Page.objects.select_subclasses().published().order_by("-pub_date")
    podcasts_queryset = Episode.objects.published().with_podcasts().order_by("-pub_date")

    def get_queryset(self):
        now = datetime.now()
        return super().get_queryset().after(now - timedelta(hours=24)).before(now).order_by("-start")

    def get_logs(self, diffusions):
        today = date.today()
        now = datetime.now()
        # diffs = Diffusion.objects.on_air().date(today)
        object_list = self.object_list
        diffs = list(object_list[: self.related_count])
        logs = Log.objects.on_air().filter(track__isnull=False, date__lte=now)
        if diffs:
            min_date = diffs[-1].start - timedelta(hours=1)
            logs = logs.after(min_date)
        else:
            logs = logs.date(today)
        return Log.merge_diffusions(
            logs, object_list, diff_count=self.related_count, count=self.related_count + 2, group_logs=True
        )

    def get_next_diffs(self):
        now = tz.now()
        query = Diffusion.objects.on_air().select_related("episode")
        current_diff = query.now(now).first()
        next_diffs = query.after(now)
        if current_diff:
            diffs = [current_diff] + list(next_diffs.exclude(pk=current_diff.pk)[:9])
        else:
            diffs = next_diffs[: self.related_carousel_count]
        return diffs

    def get_publications(self):
        # note: with postgres db, possible to use distinct()
        qs = self.publications_queryset.all()
        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.related_count:
                break
        return items

    def get_podcasts(self):
        return self.podcasts_queryset.all()[: self.related_carousel_count]

    def get_context_data(self, **kwargs):
        next_diffs = self.get_next_diffs()
        current_diff = next_diffs and next_diffs[0]

        kwargs.update(
            {
                "object": current_diff.episode,
                "diffusion": current_diff,
                "logs": self.get_logs(self.object_list),
                "next_diffs": next_diffs,
                "publications": self.get_publications(),
                "podcasts": self.get_podcasts(),
            }
        )
        return super().get_context_data(**kwargs)
