from django.db.models import Q
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.utils.translation import gettext_lazy as _
from django.views.generic.base import TemplateView

from aircox import models
from aircox.controllers.log_archiver import LogArchiver
from .base import BaseView
from .log import LogListView


__all__ = ("DashboardBaseView", "DashboardView", "StatisticsView")


class DashboardBaseView(LoginRequiredMixin, UserPassesTestMixin, BaseView):
    title = _("Dashboard")

    def test_func(self):
        user = self.request.user
        return user.is_staff or user.is_superuser


class DashboardView(DashboardBaseView, TemplateView):
    template_name = "aircox/dashboard/dashboard.html"

    def get_context_data(self, **kwargs):
        programs = models.Program.objects.editor(self.request.user)
        comments = models.Comment.objects.filter(
            Q(page__in=programs) | Q(page__episode__parent__in=programs) | Q(page__article__parent__in=programs)
        )

        kwargs.update(
            {
                "subtitle": self.request.user.get_username(),
                "programs": programs.order_by("title"),
                "comments": comments.order_by("-date"),
                "next_diffs": models.Diffusion.objects.editor(self.request.user)
                .select_related("episode")
                .after()
                .order_by("start"),
            }
        )
        return super().get_context_data(**kwargs)


class StatisticsView(DashboardBaseView, LogListView):
    template_name = "aircox/dashboard/statistics.html"
    date = None
    # redirect_date_url = "dashboard-statistics"

    # TOOD: test_func & perms check

    def get_object_list(self, logs, full=False):
        if not logs.exists():
            logs = LogArchiver().load(self.station, self.date) if self.date else []
        objs = super().get_object_list(logs, True)
        return objs
