from django.core.paginator import EmptyPage, Paginator
from django.utils.translation import gettext_lazy as _
from django.utils.functional import cached_property

from django.db.models import Aggregate, FloatField
from ..models import Event

#
#
# Useful for translation
to_be_translated = [
    _("Recurrent import name"),
    _("Add another"),
    _("Browse..."),
    _("No file selected."),
]


def get_event_qs(request):
    if request.user.is_authenticated:
        return Event.objects.filter()
    else:
        return Event.objects.filter(status=Event.STATUS.PUBLISHED)


class Median(Aggregate):
    function = "PERCENTILE_CONT"
    name = "median"
    output_field = FloatField()
    template = "%(function)s(0.5) WITHIN GROUP (ORDER BY %(expressions)s)"


class PaginatorFilter(Paginator):
    def __init__(self, filter, nb, request):
        self.request = request
        self.filter = filter

        super().__init__(filter.qs, nb)

        self.url_first_page = PaginatorFilter.update_param(
            self.request.get_full_path(), "page", 1
        )
        self.url_last_page = PaginatorFilter.update_param(
            self.request.get_full_path(), "page", self.num_pages
        )

    def update_param(params, key, value):
        p = params.split("?")
        root = p[0]
        if len(p) > 1:
            other = p[1]
            others = other.split("&")
            others = [o for o in others if not o.startswith(key)]
            others += [key + "=" + str(value)]
            return root + "?" + "&".join(others)
        else:
            return root + "?" + key + "=" + str(value)

    def page(self, *args, **kwargs):
        page = super().page(*args, **kwargs)

        try:
            page.url_previous_page = PaginatorFilter.update_param(
                self.request.get_full_path(),
                "page",
                page.previous_page_number(),
            )
        except EmptyPage:
            page.url_previous_page = self.request.get_full_path()

        try:
            page.url_next_page = PaginatorFilter.update_param(
                self.request.get_full_path(), "page", page.next_page_number()
            )
        except EmptyPage:
            page.url_next_page = self.request.get_full_path()

        return page


class PaginatorFilterCountless(PaginatorFilter):

    @cached_property
    def count(self):
        return 9999999999
