import { coerceNumberProperty, coerceBooleanProperty } from '@angular/cdk/coercion';
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, Input, Output, ViewEncapsulation, InjectionToken, Inject, Optional, Directive, } from '@angular/core';
/** The default page size if there is no page size and there are no provided page size options. */
const DEFAULT_PAGE_SIZE = 50;
/**
 * Change event object that is emitted when the user selects a
 * different page size or navigates to another page.
 */
export class PageEvent {
}
/** Injection token that can be used to provide the default options for the paginator module. */
export const R_PAGINATOR_DEFAULT_OPTIONS = new InjectionToken('R_PAGINATOR_DEFAULT_OPTIONS');
// Boilerplate for applying mixins to _RPaginatorBase.
/** @docs-private */
/**
 * Base class with all of the `RPaginator` functionality.
 * @docs-private
 */
export class _RPaginatorBase {
    constructor(_changeDetectorRef, defaults) {
        this._changeDetectorRef = _changeDetectorRef;
        this._markInitialized = () => { };
        this._pageIndex = 0;
        this._length = 0;
        this._pageSizeOptions = [];
        this._hidePageSize = false;
        this._showFirstLastButtons = false;
        /** Event emitted when the paginator changes the page size or page index. */
        this.page = new EventEmitter();
        if (defaults) {
            const { pageSize, pageSizeOptions, hidePageSize, showFirstLastButtons, } = defaults;
            if (pageSize != null) {
                this._pageSize = pageSize;
            }
            if (pageSizeOptions != null) {
                this._pageSizeOptions = pageSizeOptions;
            }
            if (hidePageSize != null) {
                this._hidePageSize = hidePageSize;
            }
            if (showFirstLastButtons != null) {
                this._showFirstLastButtons = showFirstLastButtons;
            }
        }
    }
    /** The zero-based page index of the displayed list of items. Defaulted to 0. */
    get pageIndex() { return this._pageIndex; }
    set pageIndex(value) {
        this._pageIndex = Math.max(coerceNumberProperty(value), 0);
        this._changeDetectorRef.markForCheck();
    }
    /** The length of the total number of items that are being paginated. Defaulted to 0. */
    get length() { return this._length; }
    set length(value) {
        this._length = coerceNumberProperty(value);
        this._changeDetectorRef.markForCheck();
    }
    /** Number of items to display on a page. By default set to 50. */
    get pageSize() { return this._pageSize; }
    set pageSize(value) {
        this._pageSize = Math.max(coerceNumberProperty(value), 0);
        this._updateDisplayedPageSizeOptions();
    }
    /** The set of provided page size options to display to the user. */
    get pageSizeOptions() { return this._pageSizeOptions; }
    set pageSizeOptions(value) {
        this._pageSizeOptions = (value || []).map(p => coerceNumberProperty(p));
        this._updateDisplayedPageSizeOptions();
    }
    /** Whether to hide the page size selection UI from the user. */
    get hidePageSize() { return this._hidePageSize; }
    set hidePageSize(value) {
        this._hidePageSize = coerceBooleanProperty(value);
    }
    /** Whether to show the first/last buttons UI to the user. */
    get showFirstLastButtons() { return this._showFirstLastButtons; }
    set showFirstLastButtons(value) {
        this._showFirstLastButtons = coerceBooleanProperty(value);
    }
    ngOnInit() {
        this._initialized = true;
        this._updateDisplayedPageSizeOptions();
        this._markInitialized();
    }
    ngOnDestroy() {
        this._intlChanges.unsubscribe();
    }
    /** Advances to the next page if it exists. */
    nextPage() {
        if (!this.hasNextPage()) {
            return;
        }
        const previousPageIndex = this.pageIndex;
        this.pageIndex++;
        this._emitPageEvent(previousPageIndex);
    }
    /** Move back to the previous page if it exists. */
    previousPage() {
        if (!this.hasPreviousPage()) {
            return;
        }
        const previousPageIndex = this.pageIndex;
        this.pageIndex--;
        this._emitPageEvent(previousPageIndex);
    }
    /** Move to the first page if not already there. */
    firstPage() {
        // hasPreviousPage being false implies at the start
        if (!this.hasPreviousPage()) {
            return;
        }
        const previousPageIndex = this.pageIndex;
        this.pageIndex = 0;
        this._emitPageEvent(previousPageIndex);
    }
    /** Move to the last page if not already there. */
    lastPage() {
        // hasNextPage being false implies at the end
        if (!this.hasNextPage()) {
            return;
        }
        const previousPageIndex = this.pageIndex;
        this.pageIndex = this.getNumberOfPages() - 1;
        this._emitPageEvent(previousPageIndex);
    }
    /** Whether there is a previous page. */
    hasPreviousPage() {
        return this.pageIndex >= 1 && this.pageSize != 0;
    }
    /** Whether there is a next page. */
    hasNextPage() {
        const maxPageIndex = this.getNumberOfPages() - 1;
        return this.pageIndex < maxPageIndex && this.pageSize != 0;
    }
    /** Calculate the number of pages */
    getNumberOfPages() {
        if (!this.pageSize) {
            return 0;
        }
        return Math.ceil(this.length / this.pageSize);
    }
    /**
     * Changes the page size so that the first item displayed on the page will still be
     * displayed using the new page size.
     *
     * For example, if the page size is 10 and on the second page (items indexed 10-19) then
     * switching so that the page size is 5 will set the third page as the current page so
     * that the 10th item will still be displayed.
     */
    _changePageSize(pageSize) {
        // Current page needs to be updated to reflect the new page size. Navigate to the page
        // containing the previous page's first item.
        const startIndex = this.pageIndex * this.pageSize;
        const previousPageIndex = this.pageIndex;
        this.pageIndex = Math.floor(startIndex / pageSize) || 0;
        this.pageSize = pageSize;
        this._emitPageEvent(previousPageIndex);
    }
    /** Checks whether the buttons for going forwards should be disabled. */
    _nextButtonsDisabled() {
        return this.disabled || !this.hasNextPage();
    }
    /** Checks whether the buttons for going backwards should be disabled. */
    _previousButtonsDisabled() {
        return this.disabled || !this.hasPreviousPage();
    }
    /**
     * Updates the list of page size options to display to the user. Includes making sure that
     * the page size is an option and that the list is sorted.
     */
    _updateDisplayedPageSizeOptions() {
        if (!this._initialized) {
            return;
        }
        // If no page size is provided, use the first page size option or the default page size.
        if (!this.pageSize) {
            this._pageSize = this.pageSizeOptions.length != 0 ?
                this.pageSizeOptions[0] :
                DEFAULT_PAGE_SIZE;
        }
        this._displayedPageSizeOptions = this.pageSizeOptions.slice();
        if (this._displayedPageSizeOptions.indexOf(this.pageSize) === -1) {
            this._displayedPageSizeOptions.push(this.pageSize);
        }
        // Sort the numbers using a number-specific sort function.
        this._displayedPageSizeOptions.sort((a, b) => a - b);
        this._changeDetectorRef.markForCheck();
    }
    /** Emits an event notifying that a change of the paginator's properties has been triggered. */
    _emitPageEvent(previousPageIndex) {
        this.page.emit({
            previousPageIndex,
            pageIndex: this.pageIndex,
            pageSize: this.pageSize,
            length: this.length
        });
    }
}
_RPaginatorBase.decorators = [
    { type: Directive }
];
_RPaginatorBase.ctorParameters = () => [
    { type: ChangeDetectorRef },
    null
];
_RPaginatorBase.propDecorators = {
    color: [{ type: Input }],
    pageIndex: [{ type: Input }],
    length: [{ type: Input }],
    pageSize: [{ type: Input }],
    pageSizeOptions: [{ type: Input }],
    hidePageSize: [{ type: Input }],
    showFirstLastButtons: [{ type: Input }],
    page: [{ type: Output }]
};
/**
 * Component to provide navigation between paged inforrion. Displays the size of the current
 * page, user-selectable options to change that size, what items are being shown, and
 * navigational button to go to the previous or next page.
 */
export class RPaginator extends _RPaginatorBase {
    constructor(changeDetectorRef, defaults) {
        super(changeDetectorRef, defaults);
        if (defaults && defaults.formFieldAppearance != null) {
            this._formFieldAppearance = defaults.formFieldAppearance;
        }
    }
}
RPaginator.decorators = [
    { type: Component, args: [{
                selector: 'r-paginator',
                exportAs: 'rPaginator',
                template: "<div class=\"mat-paginator-outer-container\">\r\n  <div class=\"mat-paginator-container\">\r\n    <div class=\"mat-paginator-page-size\" *ngIf=\"!hidePageSize\">\r\n      <div class=\"mat-paginator-page-size-label\">\r\n        {{_intl.itemsPerPageLabel}}\r\n      </div>\r\n\r\n      <mat-form-field\r\n        *ngIf=\"_displayedPageSizeOptions.length > 1\"\r\n        [appearance]=\"_formFieldAppearance!\"\r\n        [color]=\"color\"\r\n        class=\"mat-paginator-page-size-select\">\r\n        <mat-select\r\n          [value]=\"pageSize\"\r\n          [disabled]=\"disabled\"\r\n          [aria-label]=\"_intl.itemsPerPageLabel\"\r\n          (selectionChange)=\"_changePageSize($event.value)\">\r\n          <mat-option *ngFor=\"let pageSizeOption of _displayedPageSizeOptions\" [value]=\"pageSizeOption\">\r\n            {{pageSizeOption}}\r\n          </mat-option>\r\n        </mat-select>\r\n      </mat-form-field>\r\n\r\n      <div\r\n        class=\"mat-paginator-page-size-value\"\r\n        *ngIf=\"_displayedPageSizeOptions.length <= 1\">{{pageSize}}</div>\r\n    </div>\r\n\r\n    <div class=\"mat-paginator-range-actions\">\r\n      <div class=\"mat-paginator-range-label\">\r\n        {{_intl.getRangeLabel(pageIndex, pageSize, length)}}\r\n      </div>\r\n\r\n      <button mat-icon-button type=\"button\"\r\n              class=\"mat-paginator-navigation-first\"\r\n              (click)=\"firstPage()\"\r\n              [attr.aria-label]=\"_intl.firstPageLabel\"\r\n              [disabled]=\"_previousButtonsDisabled()\"\r\n              *ngIf=\"showFirstLastButtons\">\r\n        <svg class=\"mat-paginator-icon\" viewBox=\"0 0 24 24\" focusable=\"false\">\r\n          <path d=\"M18.41 16.59L13.82 12l4.59-4.59L17 6l-6 6 6 6zM6 6h2v12H6z\"/>\r\n        </svg>\r\n      </button>\r\n      <button mat-icon-button type=\"button\"\r\n              class=\"mat-paginator-navigation-previous\"\r\n              (click)=\"previousPage()\"\r\n              [attr.aria-label]=\"_intl.previousPageLabel\"\r\n              [disabled]=\"_previousButtonsDisabled()\">\r\n        <svg class=\"mat-paginator-icon\" viewBox=\"0 0 24 24\" focusable=\"false\">\r\n          <path d=\"M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z\"/>\r\n        </svg>\r\n      </button>\r\n      <button mat-icon-button type=\"button\"\r\n              class=\"mat-paginator-navigation-next\"\r\n              (click)=\"nextPage()\"\r\n              [attr.aria-label]=\"_intl.nextPageLabel\"\r\n              [disabled]=\"_nextButtonsDisabled()\">\r\n        <svg class=\"mat-paginator-icon\" viewBox=\"0 0 24 24\" focusable=\"false\">\r\n          <path d=\"M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z\"/>\r\n        </svg>\r\n      </button>\r\n      <button mat-icon-button type=\"button\"\r\n              class=\"mat-paginator-navigation-last\"\r\n              (click)=\"lastPage()\"\r\n              [attr.aria-label]=\"_intl.lastPageLabel\"\r\n              [matTooltip]=\"_intl.lastPageLabel\"\r\n              [matTooltipDisabled]=\"_nextButtonsDisabled()\"\r\n              [matTooltipPosition]=\"'above'\"\r\n              [disabled]=\"_nextButtonsDisabled()\"\r\n              *ngIf=\"showFirstLastButtons\">\r\n        <svg class=\"mat-paginator-icon\" viewBox=\"0 0 24 24\" focusable=\"false\">\r\n          <path d=\"M5.59 7.41L10.18 12l-4.59 4.59L7 18l6-6-6-6zM16 6h2v12h-2z\"/>\r\n        </svg>\r\n      </button>\r\n    </div>\r\n  </div>\r\n</div>\r\n",
                inputs: ['disabled'],
                host: {
                    'class': 'r-paginator',
                    'role': 'group',
                },
                changeDetection: ChangeDetectionStrategy.OnPush,
                encapsulation: ViewEncapsulation.None,
                styles: [".r-paginator{display:block}.r-paginator-outer-container{display:flex}.r-paginator-container{display:flex;align-items:center;justify-content:flex-end;padding:0 8px;flex-wrap:wrap-reverse;width:100%}.r-paginator-page-size{display:flex;align-items:baseline;margin-right:8px}[dir=rtl] .r-paginator-page-size{margin-right:0;margin-left:8px}.r-paginator-page-size-label{margin:0 4px}.r-paginator-page-size-select{margin:6px 4px 0;width:56px}.r-paginator-range-label{margin:0 32px 0 24px}.r-paginator-range-actions{display:flex;align-items:center}.r-paginator-icon{width:28px;fill:currentColor}[dir=rtl] .r-paginator-icon{transform:rotate(180deg)}"]
            },] }
];
RPaginator.ctorParameters = () => [
    { type: ChangeDetectorRef },
    { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [R_PAGINATOR_DEFAULT_OPTIONS,] }] }
];
//# sourceMappingURL=paginator.js.map