import * as _ from 'underscore';

export class PagerService {
    getPager(totalItems: number, currentPage: number = 1, pageSize: number = 12) {
        // calculate total pages
        let totalPages = Math.ceil(totalItems / pageSize);
        // console.log(totalPages);
        let startPage: number, endPage: number;
        if (totalPages <= 12) {
            // less than 12 total pages so show all
            startPage = 1;
            endPage = totalPages;
        } else {
            // more than 12 total pages so calculate start and end pages
            if (currentPage <= 6) {
                startPage = 1;
                endPage = 12;
            } else if (currentPage + 6 >= totalPages) {
                startPage = totalPages - 11;
                endPage = totalPages;
            } else {
                startPage = currentPage - 7;
                endPage = currentPage + 6;
            }
        }

        // calculate start and end item indexes
        let startIndex = (currentPage - 1) * pageSize;
        let endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1);

        // create an array of pages to ng-repeat in the pager control
        let pages = _.range(startPage, endPage + 1);

        // return object with all pager properties required by the view
        return {
            totalItems: totalItems,
            currentPage: currentPage,
            pageSize: pageSize,
            totalPages: totalPages,
            startPage: startPage,
            endPage: endPage,
            startIndex: startIndex,
            endIndex: endIndex,
            pages: pages
        };
    }
}
