from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger


class ReusablePaginationMixin:
    per_page = 10

    def get_page_number(self):
        try:
            return int(self.request.GET.get("page", 1))
        except (ValueError, TypeError):
            return 1

    def paginate_data(self, data, page_number):
        """
        Paginates data (a QuerySet or list) and returns a tuple: (page_data, pagination_context).
        """
        paginator = Paginator(data, self.per_page)
        try:
            page = paginator.page(page_number)
        except PageNotAnInteger:
            page = paginator.page(1)
        except EmptyPage:
            page = paginator.page(paginator.num_pages)

        pagination_context = {
            "number": page.number,
            "has_previous": page.has_previous(),
            "has_next": page.has_next(),
            "previous_page_number": page.previous_page_number() if page.has_previous() else 1,
            "next_page_number": page.next_page_number() if page.has_next() else paginator.num_pages,
            "paginator": {"num_pages": paginator.num_pages},
            "count": paginator.count
        }
        return page.object_list, pagination_context 