"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = __importDefault(require("react"));
var react_bootstrap_1 = require("react-bootstrap");
var lodash_1 = __importDefault(require("lodash"));
var classnames_1 = __importDefault(require("classnames"));
var Icon_1 = require("../Icon");
var Select_1 = require("../form/Select");
var Button_1 = require("../Button");
var utils_1 = require("../../../utils");
var index_en_US_1 = __importDefault(require("../../../lang/common/index-en_US"));
var CLASS_NAME_DOTS_HEAD = 'gap-left';
var CLASS_NAME_DOTS_TAIL = 'gap-right';
var CLASS_NAME_PREV_NAV = 'page-prev';
var CLASS_NAME_NEXT_NAV = 'page-next';
var CLASS_NAME_DISABLED = 'disabled';
var PAGING_MODE_LISTING = 'listing';
var PAGING_MODE_PAGES = 'pages';
var PagingMode;
(function (PagingMode) {
    PagingMode["PAGING_MODE_LISTING"] = "listing";
    PagingMode["PAGING_MODE_PAGES"] = "pages";
})(PagingMode || (PagingMode = {}));
var PurePagination = /** @class */ (function (_super) {
    __extends(PurePagination, _super);
    function PurePagination() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.handleClickPrev = function () {
            var _a = _this.props, activePage = _a.activePage, onChangePage = _a.onChangePage, onClickPrev = _a.onClickPrev;
            var prevPage = Math.max(0, activePage - 1);
            if (prevPage !== activePage) {
                onChangePage(prevPage);
            }
            onClickPrev();
        };
        _this.handleClickNext = function () {
            var _a = _this.props, onChangePage = _a.onChangePage, activePage = _a.activePage, onClickNext = _a.onClickNext;
            onChangePage(activePage + 1);
            onClickNext();
        };
        _this.handleChangePageSize = function (event) {
            var _a = event.target, value = _a.value, selectedIndex = _a.selectedIndex;
            _this.props.onChangePageSize(Number(value), selectedIndex);
        };
        return _this;
    }
    PurePagination.prototype.calculatePageCount = function (itemsCount, pageSize) {
        return Math.ceil(itemsCount / pageSize);
    };
    /**
     * Calculates pagination ranges
     *
     * @param {Number} activePage Zero based value of active page
     * @param {Number} beforeAfterAmount A number of items wanted to show before and after active page
     * @param {Number} boundaryAmount A number of items wanted to show on head and on tail
     * @param {Number} pageCount Actual count of pages
     */
    PurePagination.prototype.getRanges = function (activePage, beforeAfterAmount, boundaryAmount, pageCount) {
        var headMiddleDistance = activePage - beforeAfterAmount - boundaryAmount;
        var headSize = headMiddleDistance < 0 ? 0 : boundaryAmount;
        headSize = Math.min(headSize, pageCount);
        var lastPage = pageCount - 1;
        var middleFrom = Math.max(0, activePage - beforeAfterAmount);
        var overlappedHead = boundaryAmount - headSize;
        var headFrom = 0;
        var headTo = headFrom + headSize - 1;
        var middleSize = 1 + 2 * beforeAfterAmount;
        middleSize = middleSize + overlappedHead;
        if (middleFrom - headSize <= 1) {
            middleSize = middleSize + 1;
            middleFrom = headSize;
        }
        var middleTo = middleFrom + middleSize - 1;
        var middleTailDistance = lastPage - boundaryAmount - middleTo;
        if (middleTailDistance === 1) {
            middleTo = middleTo + 1;
        }
        else if (middleTailDistance <= 0) {
            middleFrom = middleFrom - Math.abs(middleTailDistance);
            middleFrom = middleFrom - 1;
        }
        middleFrom = Math.max(middleFrom, headSize);
        middleTo = Math.min(lastPage, middleTo);
        var tailFrom = lastPage - boundaryAmount + 1;
        tailFrom = Math.max(middleTo + 1, tailFrom);
        var tailTo = lastPage;
        var result = {
            head: [headFrom, headTo],
            middle: [middleFrom, middleTo],
            tail: [tailFrom, tailTo]
        };
        result.head = this.isRangeEmpty(result.head) ? null : result.head;
        result.middle = this.isRangeEmpty(result.middle) ? [0, 0] : result.middle;
        result.tail = this.isRangeEmpty(result.tail) ? null : result.tail;
        return result;
    };
    PurePagination.prototype.isRangeEmpty = function (range) {
        if (!range) {
            return true;
        }
        return range[1] < range[0];
    };
    PurePagination.prototype.hasGap = function (rangeA, rangeB) {
        if (this.isRangeEmpty(rangeA) || this.isRangeEmpty(rangeB)) {
            return false;
        }
        return rangeB[0] - rangeA[1] > 1;
    };
    PurePagination.prototype.hasHeadDots = function (ranges) {
        return this.hasGap(ranges.head, ranges.middle);
    };
    PurePagination.prototype.hasTailDots = function (ranges) {
        return this.hasGap(ranges.middle, ranges.tail);
    };
    PurePagination.prototype.formatPageSize = function (digit, itemsCount, pageSizes) {
        // In case of store size less/equal/ to MAX_AVAILABLE_PAGE_SIZE, visually display
        // bigger page size option as 'all'
        var maxPageSize = Math.max.apply(Math, pageSizes);
        if (digit === maxPageSize && itemsCount <= maxPageSize) {
            return utils_1.translate(this.props.allText || '');
        }
        return digit;
    };
    PurePagination.prototype.getPageSizeSelector = function (pageSizes, pageSize, itemsCount) {
        var _this = this;
        var dropdownItems = pageSizes.map(function (sizeValue, index) {
            return (react_1.default.createElement("option", { key: index, value: sizeValue, "data-test-automation-id": 'size' + index }, _this.formatPageSize(sizeValue, itemsCount, pageSizes)));
        });
        var controlId = "pageSizeSelector_" + +new Date();
        return (react_1.default.createElement(Select_1.Select, { name: "page-selector", value: pageSize, onChange: this.handleChangePageSize, className: "rc-items-per-page-selector", label: this.getPageSizeSelectorLabel(), testAutomationId: "pageSizeSelector", controlId: controlId }, dropdownItems));
    };
    PurePagination.prototype.getPageSizeSelectorLabel = function () {
        return this.props.pageSizeSelectorText;
    };
    PurePagination.prototype.getPageCount = function () {
        var _a = this.props, itemsCount = _a.itemsCount, pageSize = _a.pageSize;
        return this.calculatePageCount(itemsCount, pageSize);
    };
    PurePagination.prototype.getPageIndex = function () {
        return this.props.activePage + 1;
    };
    PurePagination.prototype.isNextButtonDisabled = function () {
        var _a = this.props, isNextButtonDisabled = _a.isNextButtonDisabled, activePage = _a.activePage;
        if (isNextButtonDisabled) {
            return isNextButtonDisabled();
        }
        return activePage >= this.getPageCount() - 1;
    };
    PurePagination.prototype.isPrevButtonDisabled = function () {
        var _a = this.props, isPrevButtonDisabled = _a.isPrevButtonDisabled, activePage = _a.activePage;
        if (typeof isPrevButtonDisabled === 'function') {
            return isPrevButtonDisabled();
        }
        return activePage <= 0;
    };
    PurePagination.prototype.renderDot = function (className) {
        return (react_1.default.createElement(Button_1.Button, { disabled: true, bsStyle: 'link', className: className }, "..."));
    };
    PurePagination.prototype.renderPages = function (range, activePage, handler) {
        var _this = this;
        if (this.isRangeEmpty(range)) {
            return [];
        }
        var _a = this.props, goToPageLabel = _a.goToPageLabel, currentPageLabel = _a.currentPageLabel;
        var list = lodash_1.default.times(range[1] - range[0] + 1, function (n) {
            var page = range[0] + n;
            var active = activePage === page;
            return (react_1.default.createElement(Button_1.Button, { "data-test-automation-id": 'p' + (page + 1), bsStyle: "link", "aria-label": goToPageLabel + " " + (page + 1) + (active ? ', ' + currentPageLabel : ''), "data-page": page, onClick: handler.bind(_this, page), key: page, active: active, disabled: active }, page + 1));
        });
        return list;
    };
    PurePagination.prototype.render = function () {
        var _a = this.props, mode = _a.mode, pageNextLabel = _a.pageNextLabel, pagePrevLabel = _a.pagePrevLabel, activePage = _a.activePage, onChangePage = _a.onChangePage, pageSizes = _a.pageSizes, pageSize = _a.pageSize, itemsCount = _a.itemsCount, beforeAfterAmount = _a.beforeAfterAmount, boundaryAmount = _a.boundaryAmount;
        var ranges = this.getRanges(activePage, beforeAfterAmount, boundaryAmount, this.getPageCount());
        var isPrevButtonDisabled = this.isPrevButtonDisabled();
        var isNextButtonDisabled = this.isNextButtonDisabled();
        var isPagesMode = mode === PAGING_MODE_PAGES;
        var prevButtonClasses = classnames_1.default(CLASS_NAME_PREV_NAV, isPrevButtonDisabled && CLASS_NAME_DISABLED);
        var prevButton = (react_1.default.createElement(Button_1.Button, { "data-test-automation-id": "prev", bsStyle: "link", "aria-label": pagePrevLabel, className: prevButtonClasses, disabled: isPrevButtonDisabled, onClick: this.handleClickPrev },
            react_1.default.createElement(Icon_1.Icon, { name: "chevron-left-small" })));
        var nextButtonClasses = classnames_1.default(CLASS_NAME_NEXT_NAV, isNextButtonDisabled && CLASS_NAME_DISABLED);
        var nextButton = (react_1.default.createElement(Button_1.Button, { "data-test-automation-id": "next", bsStyle: "link", "aria-label": pageNextLabel, className: nextButtonClasses, disabled: isNextButtonDisabled, onClick: this.handleClickNext },
            react_1.default.createElement(Icon_1.Icon, { name: "chevron-right-small" })));
        var head = this.renderPages(ranges.head, activePage, onChangePage);
        var middle = this.renderPages(ranges.middle, activePage, onChangePage);
        var tail = this.renderPages(ranges.tail, activePage, onChangePage);
        var pageSizeSelector;
        if (this.props.showPageSizeSelector) {
            pageSizeSelector = this.getPageSizeSelector(pageSizes, pageSize, itemsCount);
        }
        var cn = classnames_1.default('rc-pagination', 'form-inline rc-form-inline', this.props.className);
        return (react_1.default.createElement("div", { "aria-label": "pagination", className: cn, "data-test-automation-id": "pages" },
            pageSizeSelector,
            isPagesMode ? (react_1.default.createElement("span", { className: "form-group" },
                react_1.default.createElement(react_bootstrap_1.ButtonGroup, { bsSize: "small" },
                    prevButton,
                    head,
                    this.hasHeadDots(ranges) ? this.renderDot(CLASS_NAME_DOTS_HEAD) : null,
                    middle,
                    this.hasTailDots(ranges) ? this.renderDot(CLASS_NAME_DOTS_TAIL) : null,
                    tail,
                    nextButton))) : (react_1.default.createElement("span", { className: "form-group" },
                react_1.default.createElement(react_bootstrap_1.Row, null,
                    react_1.default.createElement(react_bootstrap_1.Col, { xs: 3 }, prevButton),
                    react_1.default.createElement(react_bootstrap_1.Col, { xs: 6, className: "text-center" },
                        react_1.default.createElement("span", { "data-test-automation-id": "label" },
                            utils_1.translate(this.props.pageLabel || ''),
                            " ",
                            this.getPageIndex())),
                    react_1.default.createElement(react_bootstrap_1.Col, { xs: 3 }, nextButton))))));
    };
    PurePagination.PagingModes = {
        listing: PAGING_MODE_LISTING,
        pages: PAGING_MODE_PAGES
    };
    PurePagination.defaultProps = {
        pageSizes: [10, 25, 50, 100, 500],
        className: null,
        showPageSizeSelector: true,
        beforeAfterAmount: 2,
        boundaryAmount: 1,
        mode: PAGING_MODE_PAGES,
        onClickNext: lodash_1.default.noop,
        onClickPrev: lodash_1.default.noop,
        get currentPageLabel() {
            return index_en_US_1.default.CURRENT_PAGE;
        },
        get goToPageLabel() {
            return index_en_US_1.default.GO_TO_PAGE;
        },
        get pageNextLabel() {
            return index_en_US_1.default.GO_TO_NEXT_PAGE;
        },
        get pagePrevLabel() {
            return index_en_US_1.default.GO_TO_PREV_PAGE;
        },
        get pageSizeSelectorText() {
            return index_en_US_1.default.SHOW;
        },
        get allText() {
            return index_en_US_1.default.ALL;
        },
        get pageLabel() {
            return ''; //FIXME [UIA-10000]
        }
    };
    return PurePagination;
}(react_1.default.Component));
exports.PurePagination = PurePagination;
//# sourceMappingURL=PurePagination.js.map