var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
import { GlobalLoaderService } from '../../../resources/global-loader/global-loader-service';
import { bindingMode, observable } from "aurelia-binding";
import { autoinject, bindable, children, customElement, processContent } from "aurelia-framework";
import { UIInternal } from '../../../utils/ui-internal';
import { ServiceBase } from '../../../data/service-base';
export var UiTablePagination = (function () {
    function UiTablePagination(globalLoaderService) {
        this.globalLoaderService = globalLoaderService;
        this.rowClassComputedFrom = [];
        this.afterLoad = null;
        this.sortBy = null;
        this.sortByDescending = false;
        this.nbRecordPerPage = 10;
        this.nbPagesToShow = 5;
        this.filter = null;
        this.selected = [];
        this.designWithBorder = false;
        this.compact = false;
        this.cellAlign = "start";
        this.headerAlign = "start";
        this.datas = [];
        this.dataToShow = [];
        this.currentPage = 1;
        this.totalPages = 1;
        this.disposables = [];
        this.columns = [];
        this.customColumns = [];
        this.pageLoaded = [];
        this.forceReload = false;
        this.nbDatas = 0;
        this.isLoading = false;
    }
    UiTablePagination.prototype.bind = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (this.service == null) {
                            console.error("Service is mandatory in UiTablePagination");
                            return [2];
                        }
                        return [4, this.computeTotalPages()];
                    case 1:
                        _a.sent();
                        this.disposables.push(UIInternal.subscribe(UIInternal.EVT_UI_TABLE_PAGINATION_RELOAD, function () { return _this.computeTotalPages(); }));
                        return [2];
                }
            });
        });
    };
    UiTablePagination.prototype.computeTotalPages = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        if (this.isLoading) {
                            return [2];
                        }
                        this.pageLoaded.splice(0);
                        _a = this;
                        return [4, this.service.getCount(this.service.gridDataSource.predicates, this.service.gridDataSource.queryParameters)];
                    case 1:
                        _a.nbDatas = _b.sent();
                        if (this.nbRecordPerPage == 0) {
                            this.nbRecordPerPage = 1;
                        }
                        this.totalPages = Math.ceil(this.nbDatas / this.nbRecordPerPage);
                        this.datas = new Array(this.nbDatas);
                        return [4, this.setData()];
                    case 2:
                        _b.sent();
                        return [2];
                }
            });
        });
    };
    UiTablePagination.prototype.unbind = function () {
        this.disposables.forEach(function (x) { return x.dispose(); });
    };
    UiTablePagination.prototype.loadData = function () {
        return __awaiter(this, void 0, void 0, function () {
            var nbDataToSkip, dataLoaded;
            var _a, _b;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        if (!(!this.isLoading && this.totalPages > 0 && !this.pageLoaded.includes(this.currentPage))) return [3, 4];
                        this.isLoading = true;
                        this.globalLoaderService.show();
                        nbDataToSkip = (this.currentPage - 1) * this.nbRecordPerPage;
                        return [4, this.service.getEntities(this.service.gridDataSource.predicates, this.service.gridDataSource.expands, this.service.gridDataSource.queryParameters, {
                                propertyPaths: this.sortBy,
                                isDescending: this.sortByDescending,
                            }, {
                                take: this.nbRecordPerPage,
                                skip: nbDataToSkip
                            })];
                    case 1:
                        dataLoaded = _c.sent();
                        if (this.forceReload) {
                            this.datas.splice(0);
                            (_a = this.datas).push.apply(_a, __spreadArray([], __read(dataLoaded), false));
                        }
                        else {
                            (_b = this.datas).splice.apply(_b, __spreadArray([nbDataToSkip, dataLoaded.length], __read(dataLoaded), false));
                        }
                        this.pageLoaded.push(this.currentPage);
                        if (!(this.afterLoad != null)) return [3, 3];
                        return [4, this.afterLoad(dataLoaded)];
                    case 2:
                        _c.sent();
                        _c.label = 3;
                    case 3:
                        this.globalLoaderService.hide();
                        this.isLoading = false;
                        _c.label = 4;
                    case 4: return [2];
                }
            });
        });
    };
    UiTablePagination.prototype.setData = function () {
        return __awaiter(this, void 0, void 0, function () {
            var dataToShowToAdd;
            var _a, _b;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0: return [4, this.loadData()];
                    case 1:
                        _c.sent();
                        dataToShowToAdd = this.datas.slice().splice((this.currentPage - 1) * this.nbRecordPerPage, this.nbRecordPerPage);
                        if (this.forceReload) {
                            this.dataToShow.splice(0);
                            (_a = this.dataToShow).push.apply(_a, __spreadArray([], __read(dataToShowToAdd), false));
                        }
                        else {
                            (_b = this.dataToShow).splice.apply(_b, __spreadArray([0, this.dataToShow.length], __read(dataToShowToAdd), false));
                        }
                        return [2];
                }
            });
        });
    };
    UiTablePagination.prototype.refresh = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.forceReload = true;
                        this.currentPage = 1;
                        this.pageLoaded.splice(0);
                        return [4, this.setData()];
                    case 1:
                        _a.sent();
                        this.forceReload = false;
                        return [2];
                }
            });
        });
    };
    UiTablePagination.prototype.columnsChanged = function () {
        this.customColumns = this.columns;
    };
    UiTablePagination.prototype.currentPageChanged = function (newValue, oldValue) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(oldValue != null && newValue != oldValue && !this.forceReload)) return [3, 2];
                        return [4, this.setData()];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2: return [2];
                }
            });
        });
    };
    UiTablePagination.prototype.goToLastPage = function () {
        this.currentPage = this.totalPages;
    };
    __decorate([
        bindable({ defaultBindingMode: bindingMode.oneTime }),
        __metadata("design:type", Object)
    ], UiTablePagination.prototype, "rowClassComputedFrom", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Object)
    ], UiTablePagination.prototype, "rowClass", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Function)
    ], UiTablePagination.prototype, "onRowClicked", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", ServiceBase)
    ], UiTablePagination.prototype, "service", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Function)
    ], UiTablePagination.prototype, "afterLoad", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", String)
    ], UiTablePagination.prototype, "sortBy", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Boolean)
    ], UiTablePagination.prototype, "sortByDescending", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Object)
    ], UiTablePagination.prototype, "nbRecordPerPage", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Object)
    ], UiTablePagination.prototype, "nbPagesToShow", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", String)
    ], UiTablePagination.prototype, "defaultSortProperty", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", String)
    ], UiTablePagination.prototype, "defaultSortOrder", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Function)
    ], UiTablePagination.prototype, "filter", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Function)
    ], UiTablePagination.prototype, "dragDropFunction", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Boolean)
    ], UiTablePagination.prototype, "showCounter", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Boolean)
    ], UiTablePagination.prototype, "checkable", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Array)
    ], UiTablePagination.prototype, "selected", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Number)
    ], UiTablePagination.prototype, "nbSelectedMax", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Boolean)
    ], UiTablePagination.prototype, "designWithBorder", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Boolean)
    ], UiTablePagination.prototype, "compact", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Function)
    ], UiTablePagination.prototype, "rowRoute", void 0);
    __decorate([
        bindable,
        __metadata("design:type", String)
    ], UiTablePagination.prototype, "cellAlign", void 0);
    __decorate([
        bindable,
        __metadata("design:type", String)
    ], UiTablePagination.prototype, "headerAlign", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Function)
    ], UiTablePagination.prototype, "onRowSelected", void 0);
    __decorate([
        observable,
        __metadata("design:type", Object)
    ], UiTablePagination.prototype, "currentPage", void 0);
    UiTablePagination = __decorate([
        customElement('ui-table-pagination'),
        autoinject,
        children({ name: 'columns', selector: ['ui-column', 'ui-table-action'] }),
        processContent(function (compiler, resources, node, instruction) {
            instruction.inheritBindingContext = true;
            return true;
        }),
        __metadata("design:paramtypes", [GlobalLoaderService])
    ], UiTablePagination);
    return UiTablePagination;
}());

//# sourceMappingURL=ui-table-pagination.js.map
