import math

from flask import Request, url_for

from src.utils.utils import limit_int, parse_int


class Pagination:
    def __init__(self, request: Request) -> None:
        self.current_page: int = parse_int(request.args.get("page"), 1)
        self.limit: int = limit_int(int(request.args.get("limit") or 25), 25)
        self.offset: int = self.calculate_offset(self.current_page, self.limit)
        self.base: dict[str, str] = request.args.to_dict()

        self.base.pop("page", None)

        self.count: int | None = None
        self.current_count: int | None = None
        self.total_pages: int | None = None

    def add_count(self, count: int):
        self.count = count
        self.current_count = self.offset + self.limit if self.offset + self.limit < self.count else self.count
        self.total_pages = math.ceil(self.count / self.limit) or 1

    def calculate_offset(self, current_page: int, limit: int):
        if current_page > 1:
            offset = (current_page - 1) * limit
        else:
            offset = 0

        return offset

    def create_paged_url(self, request: Request, page_number: int):
        return url_for(request.endpoint, page=page_number, **self.base)
