import collections.abc

from django.utils.translation import gettext_lazy as _


class InvalidPage(Exception):  # noqa: D101
    pass


class PageNotAnInteger(InvalidPage):  # noqa: D101
    pass


class EmptyPage(InvalidPage):  # noqa: D101
    pass


class MeilisearchPaginator:
    """Class for paginating search results from MeiliSearch."""

    # Translators: String used to replace omitted page numbers in elided page
    # range generated by paginators, e.g. [1, 2, '…', 5, 6, 7, '…', 9, 10].
    ELLIPSIS = _("…")

    def __init__(self, search_results):
        self.object_list = search_results.get("hits", [])
        self.per_page = search_results.get("hitsPerPage", 0)
        self.num_pages = search_results.get("totalPages", 0)
        self.count = search_results.get("totalHits", 0)

    def validate_number(self, number):
        # Convert the number to an integer or raise PageNotAnInteger
        try:
            number = int(number)
        except (TypeError, ValueError) as err:
            raise PageNotAnInteger("That page number is not an integer") from err
        if number < 1:
            raise EmptyPage("That page number is less than 1")
        return number

    def page(self, number):
        number = self.validate_number(number)
        return Page(self.object_list, number, self)

    @property
    def page_range(self):
        """Return a 1-based range of pages for iterating through within a template for loop."""
        return range(1, self.num_pages + 1)

    def get_elided_page_range(self, number=1, *, on_each_side=3, on_ends=2):
        """Return a 1-based range of pages with some values elided.

        If the page range is larger than a given size, the whole range is not
        provided and a compact form is returned instead, e.g. for a paginator
        with 50 pages, if page 43 were the current page, the output, with the
        default arguments, would be:

            1, 2, …, 40, 41, 42, 43, 44, 45, 46, …, 49, 50.
        """
        if self.num_pages <= (on_each_side + on_ends) * 2:
            yield from self.page_range
            return

        if number > (1 + on_each_side + on_ends) + 1:
            yield from range(1, on_ends + 1)
            yield self.ELLIPSIS
            yield from range(number - on_each_side, number + 1)
        else:
            yield from range(1, number + 1)

        if number < (self.num_pages - on_each_side - on_ends) - 1:
            yield from range(number + 1, number + on_each_side + 1)
            yield self.ELLIPSIS
            yield from range(self.num_pages - on_ends + 1, self.num_pages + 1)
        else:
            yield from range(number + 1, self.num_pages + 1)


class Page(collections.abc.Sequence):
    """A single page of search results."""

    def __init__(self, object_list, number, paginator):
        self.object_list = list(object_list)
        self.number = number
        self.paginator = paginator

    def __repr__(self):
        return "<Page %s of %s>" % (self.number, self.paginator.num_pages)

    def __len__(self):
        return len(self.object_list)

    def __getitem__(self, index):
        if not isinstance(index, (int, slice)):
            raise TypeError("Page indices must be integers or slices, not %s." % type(index).__name__)
        # The object_list is converted to a list so that if it was a QuerySet
        # it won't be a database hit per __getitem__.
        return self.object_list[index]

    def has_next(self):
        return self.number < self.paginator.num_pages

    def has_previous(self):
        return self.number > 1

    def has_other_pages(self):
        return self.has_previous() or self.has_next()

    def next_page_number(self):
        return self.paginator.validate_number(self.number + 1)

    def previous_page_number(self):
        return self.paginator.validate_number(self.number - 1)

    def start_index(self):
        """Return the 1-based index of the first object on this page, relative to total objects in the paginator."""
        # Special case, return zero if no items.
        if self.paginator.count == 0:
            return 0
        return (self.paginator.per_page * (self.number - 1)) + 1

    def end_index(self):
        """Return the 1-based index of the last object on this page, relative to total objects found (hits)."""
        # Special case for the last page because there can be orphans.
        if self.number == self.paginator.num_pages:
            return self.paginator.count
        return self.number * self.paginator.per_page
