from datetime import datetime

from django.contrib.auth.mixins import PermissionRequiredMixin
from django.contrib.messages.views import SuccessMessageMixin
from django.urls import reverse_lazy
from django.db.models import F, Q
from django.views.generic import ListView, UpdateView, CreateView, DeleteView
from django.utils.translation import gettext_lazy as _

from . import get_event_qs
from ..models import Organisation


class OrganisationListView(ListView):
    model = Organisation
    paginate_by = 10
    ordering = ["name__unaccent"]


class OrganisationDetailView(ListView):
    model = Organisation
    template_name = "agenda_culturel/organisation_detail.html"
    paginate_by = 10

    def get_queryset(self):
        self.organisation = (
            Organisation.objects.filter(pk=self.kwargs["pk"])
            .prefetch_related("organised_events")
            .first()
        )
        return (
            get_event_qs(self.request)
            .filter(organisers__in=[self.kwargs["pk"]])
            .filter(
                Q(other_versions__isnull=True)
                | Q(other_versions__representative=F("pk"))
                | Q(other_versions__representative__isnull=True)
            )
            .filter(start_day__gte=datetime.now())
            .order_by("start_day")
        )

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["object"] = self.organisation
        return context


class OrganisationDetailViewPast(OrganisationDetailView):
    def get_queryset(self):
        self.organisation = (
            Organisation.objects.filter(pk=self.kwargs["pk"])
            .prefetch_related("organised_events")
            .first()
        )
        self.past = True
        return (
            get_event_qs(self.request)
            .filter(organisers__in=[self.kwargs["pk"]])
            .filter(
                Q(other_versions__isnull=True)
                | Q(other_versions__representative=F("pk"))
                | Q(other_versions__representative__isnull=True)
            )
            .filter(start_day__lte=datetime.now())
            .order_by("-start_day")
        )

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["past"] = self.past
        return context


class OrganisationUpdateView(PermissionRequiredMixin, SuccessMessageMixin, UpdateView):
    model = Organisation
    permission_required = "agenda_culturel.change_organisation"
    success_message = _("The organisation has been successfully updated.")
    fields = "__all__"


class OrganisationCreateView(PermissionRequiredMixin, SuccessMessageMixin, CreateView):
    model = Organisation
    permission_required = "agenda_culturel.add_organisation"
    success_message = _("The organisation has been successfully created.")
    fields = "__all__"


class OrganisationDeleteView(PermissionRequiredMixin, DeleteView):
    model = Organisation
    permission_required = "agenda_culturel.delete_organisation"
    success_url = reverse_lazy("view_organisations")
