"use strict";
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));
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.UITable = void 0;
var aurelia_templating_resources_1 = require("aurelia-templating-resources");
var ui_column_1 = require("./ui-column");
var constants_1 = require("../../../constants/constants");
var aurelia_framework_1 = require("aurelia-framework");
var ui_data_source_1 = require("./ui-data-source");
var body_cell_1 = require("./body-cell");
var header_cell_1 = require("./header-cell");
var ui_internal_1 = require("../../../utils/ui-internal");
var ui_table_action_1 = require("./ui-table-action");
var dragula_1 = __importDefault(require("dragula"));
var date_utils_1 = require("../../../utils/date-utils");
var UITable = exports.UITable = (function () {
    function UITable(element, bindingEngine, signaler, dateUtils) {
        this.element = element;
        this.bindingEngine = bindingEngine;
        this.signaler = signaler;
        this.dateUtils = dateUtils;
        this.filter = null;
        this.selected = [];
        this.designWithBorder = false;
        this.compact = false;
        this.rowClassComputedFrom = [];
        this.cellAlign = "start";
        this.headerAlign = "start";
        this.useVirtualization = true;
        this.focusData = null;
        this.isRendered = false;
        this.isLoadingData = false;
        this.disposables = [];
        this.isDesktopScreen = true;
        this.isColumnsInitialized = false;
        this.columns = [];
        this.headersVisible = [];
        this.columnsVisible = [];
        this.isDrangAndDropPending = false;
        this.computedFromSubscriptions = [];
        this.draggableHandleClassName = "ui-table__draggable-handle";
        this.recordChangedSignal = 'ui-table-record-changed';
        this.isDesktopScreen = window.innerWidth > constants_1.CSSBreakpoints.md;
    }
    Object.defineProperty(UITable.prototype, "nbHeadersVisible", {
        get: function () {
            return this.headersVisible.length + (this.checkable ? 1 : 0) + (this.showCounter ? 1 : 0);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(UITable.prototype, "tableClasses", {
        get: function () {
            return [
                this.designWithBorder ? 'ui-table-with-border' : '',
                this.compact ? 'ui-table-compact' : ''
            ].join(' ');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(UITable.prototype, "canDragAndDrop", {
        get: function () {
            return this.isDesktopScreen && this.dragDropFunction != null;
        },
        enumerable: false,
        configurable: true
    });
    UITable.prototype.filterChanged = function () {
        var _a;
        (_a = this.ds) === null || _a === void 0 ? void 0 : _a.deboucePerformFilter();
    };
    UITable.prototype.refresh = function () {
        var _this = this;
        this.isRendered = false;
        setTimeout(function () {
            ui_internal_1.UIInternal.broadcast(ui_internal_1.UIInternal.EVT_UI_TABLE_BODY_CELL_CHANGED + "_".concat(_this.auTargetId));
        }, 200);
    };
    UITable.prototype.attached = function () {
        var _this = this;
        if (this.element) {
            this.auTargetId = parseInt($(this.element).attr('au-target-id'));
        }
        this.computeTemplateWidth();
        this.disposables.push(ui_internal_1.UIInternal.subscribe(ui_internal_1.UIInternal.EVT_VIEWPORT_CSS_BREAKPOINT_CHANGE, function (data) {
            _this.isDesktopScreen = data > constants_1.CSSBreakpoints.md;
            _this.computeTemplateWidth();
            _this.initDrake();
        }), ui_internal_1.UIInternal.subscribe(ui_internal_1.UIInternal.EVT_UI_TABLE_REFRESH + "_".concat(this.auTargetId), function () {
            _this.computeTemplateWidth();
        }), this.bindingEngine.collectionObserver(this.columns).subscribe(function (changeRecords) {
            if (changeRecords.length > 0) {
                _this.columnsChanged();
            }
        }));
        ui_internal_1.UIInternal.queueMicroTask(function () {
            _this.initDrake();
        });
    };
    UITable.prototype.detached = function () {
        var _a, _b;
        (_a = this.disposables) === null || _a === void 0 ? void 0 : _a.forEach(function (disposable) { return disposable.dispose(); });
        (_b = this.drake) === null || _b === void 0 ? void 0 : _b.destroy();
    };
    UITable.prototype.bind = function () {
        var _this = this;
        this.checkable = this.checkable || this.element.hasAttribute("checkable");
        this.showCounter = this.showCounter || this.element.hasAttribute("counter");
        this.dataHasChanged();
        this.customColumnsChanged();
        this.disposables.push(this.bindingEngine.collectionObserver(this.data).subscribe(function (changeRecords) {
            _this.isLoadingData = true;
            _this.signaler.signal(constants_1.SignalBindings.RefreshUiTableLoadingData);
            _this.signaler.signal(constants_1.SignalBindings.RefreshUiTableCheck);
            _this.dataHasChanged(changeRecords);
            _this.initDrake();
            _this.isLoadingData = false;
            _this.signaler.signal(constants_1.SignalBindings.RefreshUiTableLoadingData);
        }), this.bindingEngine.propertyObserver(this, "showCounter").subscribe(function () {
            _this.computeTemplateWidth();
        }), this.bindingEngine.propertyObserver(this, "checkable").subscribe(function () {
            _this.computeTemplateWidth();
        }));
    };
    UITable.prototype.toggleSelection = function ($event, record) {
        if (this.selected == null) {
            this.selected = [];
        }
        if ($event.detail.checked) {
            this.selected.push(record);
            if (this.nbSelectedMax != null) {
                if (this.selected.length > this.nbSelectedMax) {
                    this.selected.splice(0, this.selected.length - this.nbSelectedMax);
                }
            }
        }
        else {
            this.selected.remove(record);
        }
    };
    UITable.prototype.toggleSelectionAll = function () {
        var _a;
        var _this = this;
        if (this.selected.length === 0) {
            this.selected.splice(0);
            (_a = this.selected).push.apply(_a, __spreadArray([], __read(this.ds.data.filter(function (x) { return _this.onRowSelected == null || _this.onRowSelected({ x: x }); })), false));
        }
        else {
            this.selected.splice(0);
        }
        this.signaler.signal(constants_1.SignalBindings.RefreshUiTableCheck);
    };
    UITable.prototype.getRowClass = function (record) {
        if (this.rowClass != null) {
            if (typeof this.rowClass == 'string') {
                return this.rowClass;
            }
            else {
                return this.rowClass(record, this.isDesktopScreen);
            }
        }
    };
    UITable.prototype.dataHasChanged = function (splices) {
        var _a;
        if (isArray(this.data)) {
            (_a = this.ds) === null || _a === void 0 ? void 0 : _a.dispose();
            this.ds = new ui_data_source_1.UIDataSource(this.data, {
                defaultSortProperty: this.defaultSortProperty,
                defaultSortOrder: this.defaultSortOrder,
                filter: this.filter
            }, this.dateUtils);
        }
        this.setupRowClassObservers(splices);
        if (this.ds.data == null || this.ds.data.length == 0) {
            this.isRendered = true;
        }
    };
    UITable.prototype.setupRowClassObservers = function (splices) {
        if (this.rowClass && typeof (this.rowClass) == 'function' && this.rowClassComputedFrom) {
            var computedFrom_1 = typeof (this.rowClassComputedFrom) == 'string' ?
                [this.rowClassComputedFrom] : this.rowClassComputedFrom;
            if (splices != null) {
                for (var i = 0; i < splices.length; i++) {
                    var splice = splices[i];
                    var valuesAdded = this.data.slice(splice.index, splice.index + splice.addedCount);
                    if (valuesAdded.length > 0) {
                        this.observeRecordChanges(computedFrom_1, valuesAdded);
                    }
                    if (splice.removed.length > 0) {
                        this.disposeRecordChanges(splice.removed);
                    }
                }
            }
            else {
                this.observeRecordChanges(computedFrom_1, this.data);
            }
        }
    };
    UITable.prototype.observeRecordChanges = function (computedFrom, records) {
        var _this = this;
        records.forEach(function (record) {
            return computedFrom.forEach(function (prop) {
                return _this.computedFromSubscriptions.push({
                    subscription: _this.bindingEngine.expressionObserver(record, prop).subscribe(function () {
                        return _this.signaler.signal(_this.recordChangedSignal);
                    }),
                    record: record,
                });
            });
        });
    };
    UITable.prototype.disposeRecordChanges = function (records) {
        for (var i = this.computedFromSubscriptions.length - 1; i >= 0; --i) {
            var x = this.computedFromSubscriptions[i];
            if (records.some(function (y) { return y == x.record; })) {
                x.subscription.dispose();
                this.computedFromSubscriptions.splice(i, 1);
            }
        }
        ;
    };
    UITable.prototype.columnsChanged = function () {
        var _this = this;
        if (!this.isColumnsInitialized) {
            if (this.showCounter) {
                this.createColumn('counter');
            }
            if (this.checkable) {
                this.createColumn('checkbox');
            }
            if (this.canDragAndDrop) {
                this.createColumn('drag');
            }
        }
        this.isColumnsInitialized = true;
        this.computeTemplateWidth();
        this.columns.forEach(function (c) {
            if (!c.tableAuTargetId) {
                c.tableAuTargetId = _this.auTargetId;
            }
        });
    };
    UITable.prototype.createColumn = function (type) {
        var newColumn = new ui_column_1.UIColumn(this.element, null, null, null, this.bindingEngine);
        newColumn.type = type;
        newColumn.order = 'auto';
        newColumn.width = 'fit-content';
        this.columns.splice(0, 0, newColumn);
    };
    UITable.prototype.initDrake = function () {
        var _this = this;
        setTimeout(function () {
            var _a;
            if (_this.canDragAndDrop) {
                var allContainers = $(_this.element).find('.draggable');
                if (_this.drake != null) {
                    _this.drake.destroy();
                    _this.drake = null;
                }
                _this.drake = new dragula_1.default(allContainers.toArray(), {
                    copy: false,
                    moves: function (el, source, handle, sibling) {
                        return handle != null && handle.classList.contains(_this.draggableHandleClassName) && !_this.isDrangAndDropPending;
                    },
                    revertOnSpill: true
                })
                    .on('drop', function (el, target, source, sibling, itemVM, siblingVM) { return __awaiter(_this, void 0, void 0, function () {
                    var initialIndex, initialOrder, previousElement, finalOrder, previousElementIndex, dragAndDropResult, error_1;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                _a.trys.push([0, 2, 3, 4]);
                                this.isDrangAndDropPending = true;
                                initialIndex = el['currentIndex'];
                                initialOrder = initialIndex + 1;
                                previousElement = el.previousElementSibling;
                                finalOrder = 0;
                                if (previousElement == null || previousElement['currentIndex'] == null) {
                                    finalOrder = 1;
                                }
                                else {
                                    previousElementIndex = previousElement['currentIndex'];
                                    if (initialIndex < previousElementIndex) {
                                        finalOrder = previousElement['currentIndex'] + 1;
                                    }
                                    else {
                                        finalOrder = previousElement['currentIndex'] + 2;
                                    }
                                }
                                this.drake.cancel(true);
                                return [4, this.dragDropFunction({ record: el['viewModel'], oldVal: initialOrder, newVal: finalOrder })];
                            case 1:
                                dragAndDropResult = _a.sent();
                                return [3, 4];
                            case 2:
                                error_1 = _a.sent();
                                console.error('error when dropping element', error_1);
                                return [3, 4];
                            case 3:
                                this.isDrangAndDropPending = false;
                                return [7];
                            case 4: return [2];
                        }
                    });
                }); });
            }
            else {
                (_a = _this.drake) === null || _a === void 0 ? void 0 : _a.destroy();
            }
        }, 500);
    };
    UITable.prototype.computeTemplateWidth = function () {
        var _this = this;
        if (this.isColumnsInitialized === false)
            return;
        if (this.checkable != null && this.showCounter != null && this.columns != null) {
            var orderedColumns = this.sortColumns(this.columns);
            this.columnsVisible = orderedColumns.filter(function (col) { return col.isVisible && (col instanceof ui_table_action_1.UITableAction || ((_this.isDesktopScreen && !col.hideOnLarge) || (!_this.isDesktopScreen && !col.hideOnSmall))); });
            this.headersVisible = this.columnsVisible.filter(function (col) { return col instanceof ui_table_action_1.UITableAction || ((_this.isDesktopScreen && !col.noHeaderOnLarge) || (!_this.isDesktopScreen && !col.noHeaderOnSmall)); });
            var sumProportionalWidths_1 = 0;
            var fixedWidths_1 = [];
            this.headersVisible.forEach(function (col) {
                if (!(col instanceof ui_table_action_1.UITableAction) && col.width != null && col.width != 0 && col.width != 'fit-content') {
                    var width = col.width.toString();
                    if (isNaN(width)) {
                        fixedWidths_1.push(width);
                    }
                    else {
                        sumProportionalWidths_1 += parseFloat(width);
                    }
                }
            });
            var remainingWidthForProportional_1 = fixedWidths_1.length == 0 ? '100%'
                : "calc(100% - ".concat(fixedWidths_1.join(' - '), ")");
            this.headersVisible.forEach(function (col) {
                if (col.headerAlign == null) {
                    col.headerAlign = _this.headerAlign;
                }
                if (col instanceof ui_table_action_1.UITableAction) {
                    col.computedWidth = "auto";
                }
                else {
                    if (col.width == null || col.width == 0) {
                        col.computedWidth = "auto";
                    }
                    else if (col.width == 'fit-content') {
                        col.computedWidth = "auto";
                    }
                    else {
                        var width = col.width.toString();
                        if (isNaN(width)) {
                            col.computedWidth = width;
                        }
                        else {
                            col.computedWidth = "calc(".concat(remainingWidthForProportional_1, " * ").concat(parseFloat(width) / sumProportionalWidths_1, ")");
                        }
                    }
                }
            });
            this.columnsVisible.forEach(function (col) {
                if (col.cellAlign == null) {
                    col.cellAlign = _this.cellAlign;
                }
            });
        }
    };
    UITable.prototype.sortColumns = function (columnsVisible) {
        var autoCols = columnsVisible.filter(function (c) { return c.order == 'auto'; });
        var fixedCols = columnsVisible.filter(function (c) { return c.order != 'auto'; });
        fixedCols.forEach(function (c) {
            autoCols.splice(c.order, 0, c);
        });
        return autoCols;
    };
    UITable.prototype.renderCell = function (cell) {
        var _this = this;
        if (this.isRendered === false) {
            setTimeout(function () {
                _this.isRendered = true;
            }, 50);
        }
    };
    UITable.prototype.customColumnsChanged = function () {
        this.addCustomColumns();
    };
    UITable.prototype.addCustomColumns = function () {
        var _a;
        var _b, _c;
        if (((_b = this.customColumns) === null || _b === void 0 ? void 0 : _b.length) > 0) {
            (_c = this.columns) !== null && _c !== void 0 ? _c : (this.columns = []);
            (_a = this.columns).push.apply(_a, __spreadArray([], __read(this.customColumns), false));
        }
    };
    __decorate([
        (0, aurelia_framework_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.toView }),
        __metadata("design:type", Array)
    ], UITable.prototype, "data", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", String)
    ], UITable.prototype, "defaultSortProperty", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", String)
    ], UITable.prototype, "defaultSortOrder", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Function)
    ], UITable.prototype, "filter", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Function)
    ], UITable.prototype, "dragDropFunction", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Boolean)
    ], UITable.prototype, "showCounter", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Boolean)
    ], UITable.prototype, "checkable", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Array)
    ], UITable.prototype, "selected", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Number)
    ], UITable.prototype, "nbSelectedMax", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", Array)
    ], UITable.prototype, "customColumns", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Boolean)
    ], UITable.prototype, "designWithBorder", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Boolean)
    ], UITable.prototype, "compact", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.oneTime }),
        __metadata("design:type", Object)
    ], UITable.prototype, "rowClassComputedFrom", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Object)
    ], UITable.prototype, "rowClass", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Function)
    ], UITable.prototype, "onRowClicked", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Function)
    ], UITable.prototype, "rowRoute", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", String)
    ], UITable.prototype, "cellAlign", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", String)
    ], UITable.prototype, "headerAlign", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", Boolean)
    ], UITable.prototype, "useVirtualization", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Function)
    ], UITable.prototype, "onRowSelected", void 0);
    __decorate([
        (0, aurelia_framework_1.observable)(),
        __metadata("design:type", Object)
    ], UITable.prototype, "focusData", void 0);
    __decorate([
        (0, aurelia_framework_1.observable)(),
        __metadata("design:type", Object)
    ], UITable.prototype, "isRendered", void 0);
    __decorate([
        (0, aurelia_framework_1.observable)(),
        __metadata("design:type", Object)
    ], UITable.prototype, "isLoadingData", void 0);
    __decorate([
        (0, aurelia_framework_1.computedFrom)("headersVisible", "headersVisible.length", "checkable", "showCounter"),
        __metadata("design:type", Object),
        __metadata("design:paramtypes", [])
    ], UITable.prototype, "nbHeadersVisible", null);
    __decorate([
        (0, aurelia_framework_1.computedFrom)('designWithBorder', 'compact'),
        __metadata("design:type", String),
        __metadata("design:paramtypes", [])
    ], UITable.prototype, "tableClasses", null);
    UITable = __decorate([
        (0, aurelia_framework_1.customElement)("ui-table"),
        (0, aurelia_framework_1.children)({ name: 'columns', selector: ['ui-column', 'ui-table-action'] }),
        (0, aurelia_framework_1.viewResources)(header_cell_1.HeaderCell, body_cell_1.BodyCell),
        __metadata("design:paramtypes", [Element, aurelia_framework_1.BindingEngine, aurelia_templating_resources_1.BindingSignaler, date_utils_1.DateUtils])
    ], UITable);
    return UITable;
}());

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