import { h } from "@stencil/core";
import { randomIdGenerator } from "../../../global/utils/randomIdGenerator";
import { ButtonVariation } from "../../../enums";
/**
 * @swedishName Paginering
 */
export class NavigationPagination {
    constructor() {
        this.currentPage = undefined;
        this.twoRows = undefined;
        this.limit = 6;
        this.afInitActivePage = 1;
        this.afTotalPages = undefined;
        this.afCurrentResultStart = undefined;
        this.afId = randomIdGenerator('digi-navigation-pagination');
        this.afCurrentResultEnd = undefined;
        this.afTotalResults = 0;
        this.afResultName = '';
        this.afLimit = 6;
    }
    setTwoRows(value) {
        this.twoRows = value;
    }
    setLimit(value) {
        this.limit = value;
    }
    /**
     * Kan användas för att manuellt sätta om den aktiva sidan.
     * @en Can be used to set the active page.
     */
    async afMSetCurrentPage(pageNumber) {
        this.setCurrentPage(pageNumber, false);
    }
    /**
     * Handles which pages to display when the total amount of pages exceeds 6
     */
    getPagination(currentPage, numPages, maxLength) {
        let startPage = Math.max(currentPage - Math.floor(maxLength / 2), 1);
        let endPage = startPage + maxLength - 1;
        if (endPage > numPages) {
            endPage = numPages;
            startPage = Math.max(endPage - maxLength + 1, 1);
        }
        const pages = [];
        for (let i = startPage; i <= endPage; i++) {
            pages.push(i);
        }
        if (startPage > 1) {
            pages.shift(); //remove first array item
            pages.unshift('1…'); //add first
        }
        if (endPage < numPages) {
            pages.pop(); //remove last array item
            pages.push('…' + numPages); //add last
        }
        return pages;
    }
    get currentInterval() {
        return this.getPagination(this.currentPage, this.afTotalPages, this.limit);
    }
    prevPage() {
        this.setCurrentPage(this.currentPage - 1, true);
    }
    nextPage() {
        this.setCurrentPage(this.currentPage + 1, true);
    }
    setCurrentPage(pageToSet = this.currentPage, emitEvent = true) {
        if (pageToSet === this.currentPage) {
            return;
        }
        this.currentPage =
            pageToSet <= 1
                ? 1
                : pageToSet <= this.afTotalPages
                    ? pageToSet
                    : this.afTotalPages;
        if (emitEvent) {
            this.afOnPageChange.emit(this.currentPage);
        }
    }
    buttonAriaLabel(pageNumber) {
        return `${pageNumber}`;
    }
    handleResizeObserver(e) {
        const w = Math.round(e.detail.contentRect.width);
        if (!isNaN(w)) {
            const buttonWidth = 52;
            const minNavWidth = 570;
            if (w > minNavWidth) {
                const diff = Math.floor((w - minNavWidth) / buttonWidth);
                const minLimit = 6;
                this.setLimit(Math.min(minLimit + diff, this.afLimit));
                this.setTwoRows(false);
            }
            else {
                this.setTwoRows(true);
            }
        }
    }
    componentDidLoad() {
        this.afOnReady.emit();
    }
    componentWillLoad() {
        this.setCurrentPage(this.afInitActivePage, false);
    }
    isCurrentPage(currentPage, page) {
        if (currentPage === page || null) {
            return 'page';
        }
    }
    labelledby() {
        if (this.afTotalResults > 0) {
            return `
        ${this.afId}-aria-label
        ${this.afId}-result-show
        ${this.afId}-result-current
        ${this.afId}-result-of
        ${this.afId}-result-total
        ${this.afId}-result-name
      `;
        }
        else {
            return `${this.afId}-aria-label`;
        }
    }
    render() {
        return (h("div", { key: 'd8d99fb4bbc03f2dfba8295cf3ec8ee84bb26fce', class: "digi-navigation-pagination" }, h("digi-util-resize-observer", { key: '27084b1d413219aa3f2468beba86a5b4faf1cb75', onAfOnChange: (e) => {
                this.handleResizeObserver(e);
            } }), h("span", { key: '84e82c3caca5d9f4bcd36e132df10570f3ec431a', id: `${this.afId}-aria-label`, "aria-hidden": "true", class: "digi-navigation-pagination__aria-label" }, "Paginering"), h("nav", { key: 'e39ba4dc3ed4deb579aed3d212ef7f3310c8e9e4', "aria-labelledby": this.labelledby(), class: `digi-navigation-pagination__pagination ${this.twoRows ? 'digi-navigation-pagination--two-rows' : ''}` }, h("digi-button", { key: '684389743487f33f9a29ca418d0f1bf9a792063f', onClick: () => this.prevPage(), class: {
                'digi-navigation-pagination__button digi-navigation-pagination__button--previous': true,
                'digi-navigation-pagination__button--hidden': this.currentPage === 1
            }, afVariation: "secondary", afAriaLabel: "F\u00F6reg\u00E5ende" }, h("digi-icon-chevron-left", { key: 'c24a7960db56dde692e5c93ec08104ba706967ef', slot: "icon" }), h("span", { key: 'a71caf869f9567c1118f00a3212497410b7b43bf' }, "F\u00F6reg\u00E5ende")), h("digi-button", { key: '9ed520e00f4e5cbc1c8996ca93f2346bedefa378', onClick: () => this.nextPage(), class: {
                'digi-navigation-pagination__button digi-navigation-pagination__button--next': true,
                'digi-navigation-pagination__button--hidden': this.currentPage === this.afTotalPages
            }, afVariation: "secondary", afAriaLabel: "N\u00E4sta" }, h("digi-icon-chevron-right", { key: '9562e882499f2e0be5ea5b3dc55922ba7d49282a', slot: "icon-secondary" }), h("span", { key: '5f3234984162cc2524521606a0fb2ab645c6fb15' }, "N\u00E4sta")), h("div", { key: 'c2860112360036941893e2a5f76ab8ada71d99ff', class: "digi-navigation-pagination__pages" }, h("ol", { key: 'a7ff7c808e75ff7f60cc5e6d7a457d34ab00e49f', class: "digi-navigation-pagination__page-list" }, this.currentInterval.map((pageValue) => {
            const page = isNaN(pageValue)
                ? parseInt(pageValue.replace('…', ''))
                : pageValue;
            return (h("li", { class: `digi-navigation-pagination__page-list-item ${isNaN(pageValue) ? (page === 1 ? 'ellipsis-first' : 'ellipsis-last') : ''}` }, h("digi-button", { onClick: () => this.setCurrentPage(page), afAriaLabel: this.buttonAriaLabel(page), afAriaCurrent: this.isCurrentPage(this.currentPage, page), class: {
                    'digi-navigation-pagination__button': true,
                    'digi-navigation-pagination__page-button': true,
                    'digi-navigation-pagination__page-button--active': this.currentPage === page
                }, afVariation: this.currentPage === page
                    ? ButtonVariation.PRIMARY
                    : ButtonVariation.SECONDARY }, h("span", { class: `digi-navigation-pagination__page-text` }, page))));
        })))), this.afTotalResults > 0 && (h("div", { key: '5e6ca5150d25cbf7b2dfbd0ee9f2cfaee505d806', class: {
                'digi-navigation-pagination__result': true,
                'digi-navigation-pagination__result--pages': this.afTotalPages > 1
            }, "aria-hidden": this.afTotalPages > 1 ? 'true' : 'false', id: `${this.afId}-result` }, h("digi-typography", { key: '5b068f6c49f07a653e0779ebb1d940b54713c8fd' }, h("span", { key: '904012c7fd0cd8e7a51d2f721484c6535b69fa1e', id: `${this.afId}-result-show` }, "Visar "), h("strong", { key: 'e2bb68ef9f625cdd204732eb1015d719e859a8e2', id: `${this.afId}-result-current` }, this.afCurrentResultStart, "-", this.afCurrentResultEnd), h("span", { key: '35f11256b8a1d8478c5706f63cad06c624442305', id: `${this.afId}-result-of` }, " av "), h("strong", { key: '0b03d745dac18a6a23f7197fedc24b3d666a18db', id: `${this.afId}-result-total` }, this.afTotalResults), this.afResultName && (h("span", { key: '785a668f07a32716e5d52bf34a17e50817764212', id: `${this.afId}-result-name` }, ` ${this.afResultName}`)))))));
    }
    static get is() { return "digi-navigation-pagination"; }
    static get encapsulation() { return "scoped"; }
    static get originalStyleUrls() {
        return {
            "$": ["navigation-pagination.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["navigation-pagination.css"]
        };
    }
    static get properties() {
        return {
            "afInitActivePage": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Set initial start page"
                        }],
                    "text": "S\u00E4tter initiala aktiva sidan"
                },
                "getter": false,
                "setter": false,
                "attribute": "af-init-active-page",
                "reflect": false,
                "defaultValue": "1"
            },
            "afTotalPages": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Set total pages that exists"
                        }],
                    "text": "S\u00E4tter totala m\u00E4ngden sidor"
                },
                "getter": false,
                "setter": false,
                "attribute": "af-total-pages",
                "reflect": false
            },
            "afCurrentResultStart": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Set start value of current results"
                        }],
                    "text": "S\u00E4tter startv\u00E4rdet f\u00F6r nuvarande resultat"
                },
                "getter": false,
                "setter": false,
                "attribute": "af-current-result-start",
                "reflect": false
            },
            "afId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Input id attribute. Defaults to random string."
                        }],
                    "text": "S\u00E4tter attributet 'id'. Om inget v\u00E4ljs s\u00E5 skapas ett slumpm\u00E4ssigt id."
                },
                "getter": false,
                "setter": false,
                "attribute": "af-id",
                "reflect": false,
                "defaultValue": "randomIdGenerator('digi-navigation-pagination')"
            },
            "afCurrentResultEnd": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Set end value of current results"
                        }],
                    "text": "S\u00E4tter slutv\u00E4rdet f\u00F6r nuvarande resultat"
                },
                "getter": false,
                "setter": false,
                "attribute": "af-current-result-end",
                "reflect": false
            },
            "afTotalResults": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Set total results"
                        }],
                    "text": "S\u00E4tter totala m\u00E4ngden resultat"
                },
                "getter": false,
                "setter": false,
                "attribute": "af-total-results",
                "reflect": false,
                "defaultValue": "0"
            },
            "afResultName": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Set a result name. This is used to communicate what is being listed. For example, if the value is 'users', the component might say 'Showing 23-138 users'."
                        }],
                    "text": "S\u00E4tter ett resultatnamn. Det anv\u00E4nds f\u00F6r att kommunicera vad som listas. T.ex. om v\u00E4rdet \u00E4r 'anv\u00E4ndare' s\u00E5 kan det st\u00E5 'Visar 23-138 anv\u00E4ndare'."
                },
                "getter": false,
                "setter": false,
                "attribute": "af-result-name",
                "reflect": false,
                "defaultValue": "''"
            },
            "afLimit": {
                "type": "number",
                "mutable": true,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Set max number of pages to show in menu. Adjust automatically down to fit its container width."
                        }],
                    "text": "S\u00E4tt max antal sidor att visa i menyn. Anpassar sig efter komponentens container bredd."
                },
                "getter": false,
                "setter": false,
                "attribute": "af-limit",
                "reflect": false,
                "defaultValue": "6"
            }
        };
    }
    static get states() {
        return {
            "currentPage": {},
            "twoRows": {},
            "limit": {}
        };
    }
    static get events() {
        return [{
                "method": "afOnPageChange",
                "name": "afOnPageChange",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "When page changes"
                        }],
                    "text": "Vid byte av sida"
                },
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                }
            }, {
                "method": "afOnReady",
                "name": "afOnReady",
                "bubbles": false,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "When the component and slots are loaded and initialized this event will trigger."
                        }],
                    "text": "N\u00E4r komponenten och slotsen \u00E4r laddade och initierade s\u00E5 skickas detta eventet."
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }];
    }
    static get methods() {
        return {
            "afMSetCurrentPage": {
                "complexType": {
                    "signature": "(pageNumber: number) => Promise<void>",
                    "parameters": [{
                            "name": "pageNumber",
                            "type": "number",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "Kan anv\u00E4ndas f\u00F6r att manuellt s\u00E4tta om den aktiva sidan.",
                    "tags": [{
                            "name": "en",
                            "text": "Can be used to set the active page."
                        }]
                }
            }
        };
    }
}
