<template>
    <nav v-if="alwaysShow ? true : pageLinks && pageLinks.length > 1" v-bind="ptmi('paginatorWrapper')">
        <div v-for="(value, key) in templateItems" :key="key" ref="paginator" :class="cx('paginator', { key })" v-bind="ptm('root')">
            <div v-if="$slots.start" :class="cx('start')" v-bind="ptm('start')">
                <slot name="start" :state="currentState"></slot>
            </div>
            <template v-for="item in value" :key="item">
                <FirstPageLink v-if="item === 'FirstPageLink'" :aria-label="getAriaLabel('firstPageLabel')" :template="$slots.firstpagelinkicon" @click="changePageToFirst($event)" :disabled="isFirstPage || empty" :unstyled="unstyled" :pt="pt" />
                <PrevPageLink v-else-if="item === 'PrevPageLink'" :aria-label="getAriaLabel('prevPageLabel')" :template="$slots.prevpagelinkicon" @click="changePageToPrev($event)" :disabled="isFirstPage || empty" :unstyled="unstyled" :pt="pt" />
                <NextPageLink v-else-if="item === 'NextPageLink'" :aria-label="getAriaLabel('nextPageLabel')" :template="$slots.nextpagelinkicon" @click="changePageToNext($event)" :disabled="isLastPage || empty" :unstyled="unstyled" :pt="pt" />
                <LastPageLink v-else-if="item === 'LastPageLink'" :aria-label="getAriaLabel('lastPageLabel')" :template="$slots.lastpagelinkicon" @click="changePageToLast($event)" :disabled="isLastPage || empty" :unstyled="unstyled" :pt="pt" />
                <PageLinks v-else-if="item === 'PageLinks'" :aria-label="getAriaLabel('pageLabel')" :value="pageLinks" :page="page" @click="changePageLink($event)" :pt="pt" />
                <CurrentPageReport
                    v-else-if="item === 'CurrentPageReport'"
                    aria-live="polite"
                    :template="currentPageReportTemplate"
                    :currentPage="currentPage"
                    :pageCount="pageCount"
                    :total="total"
                    :unstyled="unstyled"
                    :pt="pt"
                />
                <RowsPerPageDropdown
                    v-else-if="item === 'RowsPerPageDropdown' && rowsPerPageOptions"
                    :aria-label="getAriaLabel('rowsPerPageLabel')"
                    :rows="d_size"
                    :options="rowsPerPageOptions"
                    @rows-change="onRowChange($event)"
                    :disabled="empty"
                    :templates="$slots"
                    :unstyled="unstyled"
                    :pt="pt"
                />
                <JumpToPageDropdown
                    v-else-if="item === 'JumpToPageDropdown'"
                    :aria-label="getAriaLabel('jumpToPageDropdownLabel')"
                    :page="page"
                    :pageCount="pageCount"
                    @page-change="changePage($event)"
                    :disabled="empty"
                    :templates="$slots"
                    :unstyled="unstyled"
                    :pt="pt"
                />
                <JumpToPageInput v-else-if="item === 'JumpToPageInput'" :page="currentPage" @page-change="changePage($event)" :disabled="empty" :unstyled="unstyled" :pt="pt" />
            </template>
            <div v-if="$slots.end" :class="cx('end')" v-bind="ptm('end')">
                <slot name="end" :state="currentState"></slot>
            </div>
        </div>
    </nav>
</template>

<script>
import { DomHandler, UniqueComponentId } from 'primevue/utils';
import BasePaginator from './BasePaginator.vue';
import CurrrentPageReport from './CurrentPageReport.vue';
import FirstPageLink from './FirstPageLink.vue';
import JumpToPageDropdown from './JumpToPageDropdown.vue';
import JumpToPageInput from './JumpToPageInput.vue';
import LastPageLink from './LastPageLink.vue';
import NextPageLink from './NextPageLink.vue';
import PageLinks from './PageLinks.vue';
import PrevPageLink from './PrevPageLink.vue';
import RowsPerPageDropdown from './RowsPerPageDropdown.vue';

export default {
    name: 'Paginator',
    extends: BasePaginator,
    inheritAttrs: false,
    emits: ['update:current', 'update:size', 'pageChange'],
    data() {
        return {
            d_current: this.current,
            d_size: this.size
        };
    },
    watch: {
        current(newValue) {
            this.d_current = newValue;
        },
        size(newValue) {
            this.d_size = newValue;
        },
    },
    mounted() {
        this.setPaginatorAttribute();
        this.createStyle();
    },
    methods: {
        changePage(p) {
            const pc = this.pageCount;

            if (p >= 1 && p <= pc) {
                this.d_current = p;
                const state = {
                    size:this.d_size,
                    total:this.total,
                    current: p,
                    pageCount: pc
                };

                this.$emit('update:current', this.d_current);
                this.$emit('update:size', this.d_size);
                this.$emit('pageChange', state);
            }
        },

        changePageToFirst(event) {
            if (!this.isFirstPage) {
                this.changePage(1);
            }
            event.preventDefault();
            event.stopPropagation();
        },
        changePageToPrev(event) {
            this.changePage(this.page - 1);
            event.preventDefault();
            event.stopPropagation();
        },
        changePageLink(event) {
            this.changePage(event.value);
            event.originalEvent.preventDefault();
            event.originalEvent.stopPropagation();
        },
        changePageToNext(event) {
            this.changePage(this.page + 1);
            event.preventDefault();
            event.stopPropagation();
        },
        changePageToLast(event) {
            if (!this.isLastPage) {
                this.changePage(this.pageCount );
            }
            event.preventDefault();
            event.stopPropagation();
        },
        onRowChange(value) {
            this.d_size = value;
            this.changePage(1);
        },
        createStyle() {
            if (this.hasBreakpoints() && !this.isUnstyled) {
                this.styleElement = document.createElement('style');
                this.styleElement.type = 'text/css';
                DomHandler.setAttribute(this.styleElement, 'nonce', this.$primevue?.config?.csp?.nonce);
                document.head.appendChild(this.styleElement);

                let innerHTML = '';

                const keys = Object.keys(this.template);
                const sortedBreakpoints = {};

                keys.sort((a, b) => parseInt(a) - parseInt(b)).forEach((key) => {
                    sortedBreakpoints[key] = this.template[key];
                });

                for (const [index, [key]] of Object.entries(Object.entries(sortedBreakpoints))) {
                    let minValue, calculatedMinValue;

                    if (key !== 'default' && typeof Object.keys(sortedBreakpoints)[index - 1] === 'string') {
                        calculatedMinValue = Number(Object.keys(sortedBreakpoints)[index - 1].slice(0, -2)) + 1 + 'px';
                    } else {
                        calculatedMinValue = Object.keys(sortedBreakpoints)[index - 1];
                    }

                    minValue = Object.entries(sortedBreakpoints)[index - 1] ? `and (min-width:${calculatedMinValue})` : '';

                    if (key === 'default') {
                        innerHTML += `
                            @media screen ${minValue} {
                                .paginator[${this.attributeSelector}],
                                    display: flex;
                                }
                            }
                        `;
                    } else {
                        innerHTML += `
.paginator[${this.attributeSelector}], .p-paginator-${key} {
    display: none;
}
@media screen ${minValue} and (max-width: ${key}) {
    .paginator[${this.attributeSelector}], .p-paginator-${key} {
        display: flex;
    }
    .paginator[${this.attributeSelector}],
    .p-paginator-default{
        display: none;
    }
}
                    `;
                    }
                }

                this.styleElement.innerHTML = innerHTML;
            }
        },
        hasBreakpoints() {
            return typeof this.template === 'object';
        },
        setPaginatorAttribute() {
            if (this.$refs.paginator && this.$refs.paginator.length >= 0) {
                [...this.$refs.paginator].forEach((el) => {
                    el.setAttribute(this.attributeSelector, '');
                });
            }
        },
        getAriaLabel(labelType) {
            return this.$primevue.config.locale.aria ? this.$primevue.config.locale.aria[labelType] : undefined;
        }
    },
    computed: {
        templateItems() {
            let keys = {};

            if (this.hasBreakpoints()) {
                keys = this.template;

                if (!keys.default) {
                    keys.default = 'FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink RowsPerPageDropdown';
                }

                for (const item in keys) {
                    keys[item] = this.template[item].split(' ').map((value) => {
                        return value.trim();
                    });
                }

                return keys;
            }

            keys['default'] = this.template.split(' ').map((value) => {
                return value.trim();
            });

            return keys;
        },
        page() {
            return this.d_current;
        },
        pageCount() {
            return Math.ceil(this.total / this.d_size);
        },
        isFirstPage() {
            return this.page === 1;
        },
        isLastPage() {
            return this.page === this.pageCount ;
        },
        calculatePageLinkBoundaries() {
            const numberOfPages = this.pageCount;
            const visiblePages = Math.min(this.pageLinkSize, numberOfPages);

            //calculate range, keep current in middle if necessary
            let start = Math.max(0, Math.ceil(this.page - visiblePages / 2));
            let end = Math.min(numberOfPages - 1, start + visiblePages - 1);

            //check when approaching to last page
            const delta = this.pageLinkSize - (end - start + 1);

            start = Math.max(0, start - delta);

            return [start, end];
        },
        pageLinks() {
            let pageLinks = [];
            let boundaries = this.calculatePageLinkBoundaries;
            let start = boundaries[0];
            let end = boundaries[1];

            for (var i = start; i <= end; i++) {
                pageLinks.push(i + 1);
            }

            return pageLinks;
        },
        currentState() {
            return {
                page: this.d_current,
                size: this.d_size
            };
        },
        empty() {
            return this.pageCount === 0;
        },
        currentPage() {
            return this.pageCount > 0 ? this.page  : 0;
        },
        attributeSelector() {
            return UniqueComponentId();
        }
    },
    components: {
        CurrentPageReport: CurrrentPageReport,
        FirstPageLink: FirstPageLink,
        LastPageLink: LastPageLink,
        NextPageLink: NextPageLink,
        PageLinks: PageLinks,
        PrevPageLink: PrevPageLink,
        RowsPerPageDropdown: RowsPerPageDropdown,
        JumpToPageDropdown: JumpToPageDropdown,
        JumpToPageInput: JumpToPageInput
    }
};
</script>
