import { r as registerInstance, c as createEvent, h, H as Host, g as getElement } from './index-ClISz4NF.js';
import { F as Fragment } from './Fragment-5itQzbON.js';
import { v as validateProp } from './props-CJZgTDla.js';
import { S as Sizes } from './sizes-BcQO4NH2.js';
import { C as Colors } from './colors-U40vKHrs.js';
import { p as pick } from './utils-CQvUntGY.js';
import { g as govHost, p as prepareClasses, t as toBoolAttrIfDefined } from './template-CoD1xawt.js';
import { c as createID } from './string.utils-vN03FcXN.js';
import { c as createArrayRange } from './array.utils-CJ0U_ONv.js';
import { A as AttributeObserver, a as ariaAttributes } from './attribute-Bz_RzYFb.js';
import { i as inheritAriaAttributes } from './accessibility-wqNV8djF.js';
import './gov.log-BtqD9K8d.js';
import './helpers.types-DNztiAH0.js';

const PaginationSizes = pick(Sizes, ['_S', '_M']);
const PaginationColors = pick(Colors, ['PRIMARY', 'NEUTRAL']);
var PaginationTypes;
(function (PaginationTypes) {
    PaginationTypes["BUTTON"] = "button";
    PaginationTypes["SELECT"] = "select";
})(PaginationTypes || (PaginationTypes = {}));
const PaginationClass = {
    root: 'gov-pagination',
    list: 'gov-pagination__list',
    item: 'gov-pagination__item',
    itemArrow: 'gov-pagination__item--arrow',
    itemMore: 'gov-pagination__item--more',
    itemSelect: 'gov-pagination__item--select',
    inner: 'gov-pagination__inner',
    arrow: 'gov-pagination__arrow',
};

function paginate(totalItems, currentPage = 1, pageSize = 10, maxPages = 10) {
    // calculate total pages
    const totalPages = Math.ceil(totalItems / pageSize);
    // ensure current page isn't out of range
    if (currentPage < 1) {
        currentPage = 1;
    }
    else if (currentPage > totalPages) {
        currentPage = totalPages;
    }
    let startPage, endPage;
    if (totalPages <= maxPages) {
        // total pages less than max so show all pages
        startPage = 1;
        endPage = totalPages;
    }
    else {
        // total pages more than max so calculate start and end pages
        const maxPagesBeforeCurrentPage = Math.floor(maxPages / 2);
        const maxPagesAfterCurrentPage = Math.ceil(maxPages / 2) - 1;
        if (currentPage <= maxPagesBeforeCurrentPage) {
            // current page near the start
            startPage = 1;
            endPage = maxPages;
        }
        else if (currentPage + maxPagesAfterCurrentPage >= totalPages) {
            // current page near the end
            startPage = totalPages - maxPages + 1;
            endPage = totalPages;
        }
        else {
            // current page somewhere in the middle
            startPage = currentPage - maxPagesBeforeCurrentPage;
            endPage = currentPage + maxPagesAfterCurrentPage;
        }
    }
    // calculate start and end item indexes
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1);
    // create an array of pages to ng-repeat in the pager control
    const pages = Array.from(Array(endPage + 1 - startPage).keys()).map(i => startPage + i);
    // 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,
    };
}

const GovPagination = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.govPage = createEvent(this, "gov-page");
        /**
         * Pagination type
         */
        this.type = "button";
        /**
         * Currently displayed page
         */
        this.current = 1;
        /**
         * Total count of entries
         */
        this.total = 0;
        /**
         * Pagination's size
         */
        this.size = "m";
        /**
         * Style variation of the pagination.
         */
        this.color = "primary";
        /**
         * Maximum number of entries per page
         */
        this.pageSize = 10;
        /**
         * Maximum pages displayed for selection
         */
        this.maxPages = 5;
        /**
         * Adds accessible label for the page select
         */
        this.accessibleSelectLabel = "Vybrat stranu";
        /**
         * Adds accessible label for the page item
         */
        this.accessiblePageLabel = "Strana";
        /**
         * Description of the possibility to go back one page
         */
        this.labelPrev = 'Přejít o stranu zpět';
        /**
         * Description of the option to go to the top of paging
         */
        this.labelStart = 'Přejít na začátek';
        /**
         * Description of the option to go to the end of paging
         */
        this.labelNext = 'Přejít na další stranu';
        /**
         * Description of the option to move one page forward
         */
        this.labelEnd = 'Přejít na konec';
        this.inheritedAttributes = {};
        this.h = govHost(this.host);
        this.pageSelectId = createID("GovPageSelect");
        this.selectId = createID("GovSelect");
    }
    validateType(newValue) {
        validateProp(PaginationTypes, newValue, PaginationClass.root);
    }
    validateSize(newValue) {
        validateProp(PaginationSizes, newValue, PaginationClass.root);
    }
    validateColor(newValue) {
        validateProp(PaginationColors, newValue, PaginationClass.root);
    }
    recalculate() {
        this.recalculatePagination(this.current);
    }
    componentDidLoad() {
        this.attributeObserver = new AttributeObserver(this.host, (attributeName, newValue) => {
            this.onAriaAttributeChange(attributeName, newValue);
        });
        this.attributeObserver.startObserving(ariaAttributes);
    }
    componentWillLoad() {
        this.recalculatePagination(this.current);
        this.validateSize(this.size);
        this.validateColor(this.color);
        this.inheritedAttributes = inheritAriaAttributes(this.host);
    }
    disconnectedCallback() {
        var _a;
        (_a = this.attributeObserver) === null || _a === void 0 ? void 0 : _a.stopObserving();
    }
    onAriaAttributeChange(attributeName, newValue) {
        this.host.removeAttribute(attributeName);
        this.inheritedAttributes = Object.assign(Object.assign({}, this.inheritedAttributes), { [attributeName]: newValue });
    }
    recalculatePagination(currentPage) {
        this.pagination = paginate(this.total, currentPage, this.pageSize, this.maxPages);
    }
    isActivePageClass(originalClass, page) {
        if (this.pagination.currentPage === page) {
            return originalClass + " is-active";
        }
        else {
            return originalClass;
        }
    }
    prepareLinkUrl(page) {
        if (this.link) {
            return String(this.link).replace("{PAGE}", String(page));
        }
        return undefined;
    }
    resetSelectValue() {
        if (this.spreadSelectRef) {
            this.spreadSelectRef.getRef()
                .then((el) => {
                el.value = '...';
            });
        }
    }
    render() {
        const pageResolver = (page, content, description) => {
            const isDisabled = page === -1;
            const ariaCurrent = toBoolAttrIfDefined(this.pagination.currentPage === page ? true : undefined);
            return (h("gov-button", { href: this.prepareLinkUrl(page), color: this.color, size: this.size, type: "base", disabled: isDisabled, "on-gov-click": (e) => this.onClickHandler(e, page), "aria-label": description ? description : page > -1 ? `${this.accessiblePageLabel} ${page}` : undefined, "aria-current": ariaCurrent, class: PaginationClass.inner, focusable: true }, content));
        };
        return (h(Host, { class: this.h.classes(PaginationClass.root), type: this.type, color: this.color, size: this.size }, h("nav", Object.assign({}, this.inheritedAttributes), h("ul", { class: PaginationClass.list }, h("li", { class: prepareClasses([PaginationClass.item, PaginationClass.itemArrow]) }, pageResolver(this.pagination.currentPage > 1 ? 1 : -1, h("gov-icon", { class: PaginationClass.arrow, name: "chevron-double-left", type: "components" }), this.labelStart)), h("li", { class: prepareClasses([PaginationClass.item, PaginationClass.itemArrow]) }, pageResolver(this.pagination.startPage < this.pagination.currentPage ? this.pagination.currentPage - 1 : -1, h("gov-icon", { class: PaginationClass.arrow, name: "chevron-left", type: "components" }), this.labelPrev)), this.type == "select" ? (h("li", { class: prepareClasses([PaginationClass.item, PaginationClass.itemSelect]) }, h("span", { class: PaginationClass.inner }, h("span", { id: this.pageSelectId, hidden: true }, this.accessibleSelectLabel), h("gov-form-select", { size: this.size, color: this.color, identifier: this.selectIdentifier || this.selectId, "aria-labelledby": this.pageSelectId, "on-gov-change": this.onSelectHandler.bind(this) }, createArrayRange(1, this.pagination.totalPages).map(page => (h("option", { value: page, selected: this.pagination.currentPage === page }, page))))))) : (h(Fragment, null, this.pagination.pages.map(page => (h("li", { class: this.isActivePageClass(PaginationClass.item, page) }, pageResolver(page, page, '')))), this.pagination.totalPages ? (h("li", { class: prepareClasses([PaginationClass.item, PaginationClass.itemMore]) }, h("span", { class: PaginationClass.inner }, h("span", { id: this.pageSelectId, hidden: true }, this.accessibleSelectLabel), h("gov-form-select", { size: this.size, color: this.color, identifier: this.selectIdentifier || this.selectId, "aria-labelledby": this.pageSelectId, ref: el => (this.spreadSelectRef = el), "on-gov-change": this.onSelectHandler.bind(this) }, h("option", { selected: true, hidden: true }, "..."), createArrayRange(1, this.pagination.totalPages).map(page => (h("option", { value: page, selected: false }, page))))))) : null)), h("li", { class: prepareClasses([PaginationClass.item, PaginationClass.itemArrow]) }, pageResolver(this.pagination.totalPages > this.pagination.currentPage ? this.pagination.currentPage + 1 : -1, h("gov-icon", { class: PaginationClass.arrow, name: "chevron-right", type: "components" }), this.labelNext)), h("li", { class: prepareClasses([PaginationClass.item, PaginationClass.itemArrow]) }, pageResolver(this.pagination.totalPages > this.pagination.currentPage ? this.pagination.totalPages : -1, h("gov-icon", { class: PaginationClass.arrow, name: "chevron-double-right", type: "components" }), this.labelEnd))))));
    }
    onClickHandler(e, page) {
        e.stopPropagation();
        this.recalculatePagination(page);
        this.govPage.emit({
            component: PaginationClass.root,
            pagination: this.pagination
        });
    }
    onSelectHandler(e) {
        e.stopPropagation();
        const value = e.detail.value;
        const page = parseInt(value);
        this.resetSelectValue();
        if (isNaN(page) === false) {
            this.recalculatePagination(page);
            if (this.link) {
                window.location.href = this.prepareLinkUrl(page);
            }
            else {
                this.govPage.emit({
                    component: PaginationClass.root,
                    pagination: this.pagination
                });
            }
        }
    }
    get host() { return getElement(this); }
    static get watchers() { return {
        "type": ["validateType"],
        "size": ["validateSize"],
        "color": ["validateColor"],
        "current": ["recalculate"],
        "total": ["recalculate"],
        "pageSize": ["recalculate"],
        "maxPages": ["recalculate"]
    }; }
};

export { GovPagination as gov_pagination };
//# sourceMappingURL=gov-pagination.entry.js.map

//# sourceMappingURL=gov-pagination.entry.js.map