import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core';

@Component({
    selector: 'redaction-pagination',
    templateUrl: './pagination.component.html',
    styleUrls: ['./pagination.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class PaginationComponent {
    displayedPages: (number | string)[];
    @Output() pageChanged = new EventEmitter<number>();
    displayed;

    private _currentPage: number;

    get currentPage() {
        return this._currentPage;
    }

    private _totalPages: number;

    get totalPages() {
        return this._totalPages;
    }

    @Input()
    set settings(value: { currentPage: number; totalPages: number }) {
        this._currentPage = value.currentPage;
        this._totalPages = value.totalPages;
        this._updatePagesArray();
    }

    selectPage(page: number | string) {
        if (page !== '...') {
            this.pageChanged.emit(page as number);
        }
    }

    displayValue(page: number | string) {
        return page === '...' ? page : (page as number) + 1;
    }

    isNumber(page) {
        return Number.isInteger(page);
    }

    private _updatePagesArray() {
        this.displayedPages = [0];
        if (Math.max(1, this.currentPage - 1) > 1) {
            this.displayedPages.push('...');
        }
        for (let page = Math.max(1, this.currentPage - 1); page <= Math.min(this.currentPage + 1, this.totalPages - 1); ++page) {
            this.displayedPages.push(page);
        }
        if (Math.min(this.currentPage + 1, this.totalPages - 1) !== this.totalPages - 1) {
            if (this.currentPage + 1 < this.totalPages - 2) {
                this.displayedPages.push('...');
            }
            this.displayedPages.push(this.totalPages - 1);
        }
    }
}
