import ngModule from '../../module';
import './style.scss';

export default class Paging {
    get numPages() {
        return Math.ceil(this.numItems / this.numPerPage);
    }

    constructor($http, $scope) {
        this.$http = $http;
        this.$scope = $scope;
        this.where = this.filter;
        this.numPerPage = null;
        this.numItems = 0;
        $scope.$watch('$ctrl.index.model.length', () => this.onModelUpdated());
    }

    $onChanges(changes) {
        if (!this.index) return;
        this.numPerPage = this.index.filter.size;
        this.currentPage = this.index.filter.page;
        if (changes.total)
            this.numItems = changes.total.currentValue;
    }

    onModelUpdated() {
        let index = this.index;
        let filter = index.filter;

        if (filter.page >= this.numPages && index.model.length >= this.numPerPage)
            this.numItems = filter.page * filter.size + 1;
    }

    onPageChange(page) {
        this.index.filter.page = page;
        if (typeof this.pageChange === 'undefined') {
            this.index.accept();
        } else {
            this.pageChange();
        }
    }
    $doCheck() {
        if (this.index && this.index.filter && this.index.filter.page && this.index.filter.page != this.currentPage) {
            this.currentPage = this.index.filter.page;
        }
    }
}
Paging.$inject = ['$http', '$scope'];

ngModule.component('vnPaging', {
    template: require('./paging.html'),
    bindings: {
        index: '<',
        pageChange: '&?',
        total: '<'
    },
    controller: Paging
});