import { isNumber } from '../predicate';
export class Pager {
    constructor(totalItems, itemsPerPage, initialPageIndex = 0) {
        this.setTotalItems = (totalItems) => {
            this.totalItems = totalItems;
            this.update();
        };
        this.setItemsPerPage = (itemsPerPage) => {
            this.itemsPerPage = itemsPerPage;
            this.update();
        };
        this.isPageable = () => this.firstItemIndex !== -1;
        this.getTotalPages = () => this.totalPages;
        this.getCurrentPageIndex = () => this.currentPageIndex;
        this.getFirstItemIndex = () => this.firstItemIndex;
        this.getLastItemIndex = () => this.lastItemIndex;
        this.hasNextPage = () => this.currentPageIndex < this.totalPages - 1;
        this.hasPreviousPage = () => this.currentPageIndex > 0;
        this.goToNextPage = () => {
            this.goToPageIndex(this.currentPageIndex + 1);
        };
        this.goToPreviousPage = () => {
            this.goToPageIndex(this.currentPageIndex - 1);
        };
        this.goToPageIndex = (pageIndex) => {
            this.currentPageIndex = pageIndex;
            this.update();
        };
        this.update = () => {
            if (this.totalItems <= 0) {
                this.totalPages = 0;
                this.currentPageIndex = 0;
                this.firstItemIndex = -1;
                this.lastItemIndex = -1;
                return;
            }
            this.totalPages = Math.ceil(this.totalItems / this.itemsPerPage);
            // Ensure the current page falls within our range of total pages.
            this.currentPageIndex = Math.min(Math.max(0, this.currentPageIndex), this.totalPages - 1);
            // Find the range of visible items on the current page.
            this.firstItemIndex = this.currentPageIndex * this.itemsPerPage;
            this.lastItemIndex =
                Math.min(this.firstItemIndex + this.itemsPerPage, this.totalItems) - 1;
        };
        if (!isNumber(totalItems) || isNaN(totalItems)) {
            throw new Error('Please provide a number of totalItems');
        }
        if (!isNumber(itemsPerPage) || isNaN(itemsPerPage)) {
            throw new Error('Please provide a number of itemsPerPage');
        }
        if (!isNumber(initialPageIndex) || isNaN(initialPageIndex)) {
            throw new Error('Please provide a number of initialPageIndex');
        }
        this.currentPageIndex = initialPageIndex;
        this.firstItemIndex = -1;
        this.itemsPerPage = itemsPerPage;
        this.lastItemIndex = -1;
        this.totalItems = totalItems;
        this.totalPages = 0;
        this.update();
    }
}
//# sourceMappingURL=pager.js.map