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 { ValidationController } from 'aurelia-validation';
import { Router } from 'aurelia-router';
import { autoinject, bindable, BindingEngine, bindingMode, computedFrom, containerless, createOverrideContext, observable, processContent, ViewSlot } from "aurelia-framework";
import { UIInternal } from "../../../utils/ui-internal";
import { UIColumn } from "./ui-column";
import { BindingSignaler } from 'aurelia-templating-resources';
import { UITableAction } from './ui-table-action';
export var BodyCell = (function () {
    function BodyCell(router, signaler, validationController, bindingEngine) {
        var _this = this;
        this.router = router;
        this.signaler = signaler;
        this.validationController = validationController;
        this.bindingEngine = bindingEngine;
        this.focusData = null;
        this.route = "test";
        this.isRendered = false;
        this.menuItemsBodyCell = [];
        this.rowClickIgnoreElements = ["A", "BUTTON", "SELECT", "INPUT", "UI-SELECT"];
        this.debounceCompile = UIInternal.debounce(function (newVersion) {
            if (newVersion === void 0) { newVersion = false; }
            _this.tryCompile(newVersion);
        }, 50);
    }
    BodyCell.prototype.bind = function (bindingContext, overrideContext) {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                this.overrideContext = overrideContext;
                UIInternal.subscribe(UIInternal.EVT_CHANGE_LANGUAGE, function () {
                    _this.setTitle();
                });
                return [2];
            });
        });
    };
    Object.defineProperty(BodyCell.prototype, "isClickable", {
        get: function () {
            return this.route != null || (this.onCellClicked != null && !this.column.isRowClickIgnore);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BodyCell.prototype, "title", {
        get: function () {
            return this._title;
        },
        enumerable: false,
        configurable: true
    });
    BodyCell.prototype.setTitle = function () {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
        this._title = '';
        if (((_a = this.view) === null || _a === void 0 ? void 0 : _a.lastChild) != null) {
            var lastChild = (_b = this.view) === null || _b === void 0 ? void 0 : _b.lastChild;
            if (lastChild.nodeName == "#text") {
                this._title = (_d = (_c = lastChild.textContent) === null || _c === void 0 ? void 0 : _c.trim()) !== null && _d !== void 0 ? _d : '';
            }
            else if (lastChild.nodeName == "#comment") {
                this._title = (_g = (_f = (_e = lastChild.previousElementSibling) === null || _e === void 0 ? void 0 : _e.innerText) === null || _f === void 0 ? void 0 : _f.trim()) !== null && _g !== void 0 ? _g : '';
            }
            else if (lastChild.nodeName == "UI-SELECT") {
                this._title = (_k = (_j = (_h = lastChild.getElementsByTagName("select")) === null || _h === void 0 ? void 0 : _h[0].innerText) === null || _j === void 0 ? void 0 : _j.trim()) !== null && _k !== void 0 ? _k : '';
            }
            else if (lastChild.nodeName == "UI-INPUT" || lastChild.nodeName == "UI-DATE-PICKER") {
                this._title = (_o = (_m = (_l = lastChild.getElementsByTagName("input")) === null || _l === void 0 ? void 0 : _l[0].value) === null || _m === void 0 ? void 0 : _m.trim()) !== null && _o !== void 0 ? _o : '';
            }
            else {
                this._title = (_q = (_p = lastChild.innerText) === null || _p === void 0 ? void 0 : _p.trim()) !== null && _q !== void 0 ? _q : '';
            }
        }
    };
    BodyCell.prototype.isActionColumn = function () {
        return this.column instanceof UITableAction || this.column.type == "action";
    };
    BodyCell.prototype.indexDragChanged = function (newValue, oldValue) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                if (newValue != oldValue) {
                    this.debounceCompile();
                }
                return [2];
            });
        });
    };
    BodyCell.prototype.attached = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!this.el) return [3, 2];
                        this.slot = new ViewSlot(this.el.firstElementChild || this.el, true);
                        UIInternal.subscribe(UIInternal.EVT_UI_TABLE_BODY_CELL_CHANGED + "_".concat(this.tableAuTargetId), function () {
                            _this.tryCompile();
                        });
                        return [4, this.processCurrentRecord()];
                    case 1:
                        _a.sent();
                        this.tryCompile();
                        _a.label = 2;
                    case 2: return [2];
                }
            });
        });
    };
    BodyCell.prototype.detached = function () {
        if (this.hasChangesSubscriptionKey != null) {
            this.currentRecord.entityAspect.propertyChanged.unsubscribe(this.hasChangesSubscriptionKey);
        }
    };
    BodyCell.prototype.internalOnCellClicked = function ($event) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!($event.target.nodeName == "A" && $event.target.hasAttribute("href"))) return [3, 1];
                        this.internalOnLinkClick($event, $event.target.href);
                        return [3, 4];
                    case 1:
                        if (!this.isRowClickAllowed($event.target)) return [3, 4];
                        if (!(this.route != null)) return [3, 2];
                        this.internalOnLinkClick($event, this.route);
                        return [3, 4];
                    case 2:
                        if (!(this.onCellClicked != null && !this.column.isRowClickIgnore)) return [3, 4];
                        return [4, this.onCellClicked({ record: this.currentRecord })];
                    case 3:
                        _a.sent();
                        _a.label = 4;
                    case 4: return [2];
                }
            });
        });
    };
    BodyCell.prototype.internalOnLinkClick = function ($event, route) {
        if ($event.ctrlKey) {
            window.open(route, "_blank");
        }
        else {
            this.router.navigate(route);
        }
    };
    BodyCell.prototype.isRowClickAllowed = function (target) {
        return target == this.el || target == this.el.parentElement || (this.rowClickIgnoreElements.includes(this.view.firstChild.nodeName) == false && this.rowClickIgnoreElements.includes(target.nodeName) == false);
    };
    BodyCell.prototype.currentRecordChanged = function (newValue, oldValue) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (newValue == null)
                            return [2];
                        return [4, this.processCurrentRecord()];
                    case 1:
                        _a.sent();
                        this.debounceCompile(true);
                        return [2];
                }
            });
        });
    };
    BodyCell.prototype.tableAuTargetIdChanged = function () {
        var _this = this;
        UIInternal.subscribe(UIInternal.EVT_UI_TABLE_BODY_CELL_CHANGED + "_".concat(this.tableAuTargetId), function () {
            _this.tryCompile();
            _this.signaler.signal('refresh_cell');
        });
    };
    BodyCell.prototype.tryCompile = function (newVersion) {
        var _this = this;
        if (newVersion === void 0) { newVersion = false; }
        UIInternal.queueMicroTask(function () {
            _this.compileCell(_this.el, newVersion);
            _this.validateCurrentRecord();
        });
    };
    BodyCell.prototype.validateCurrentRecord = function () {
        var _this = this;
        if (this.currentRecord == null)
            return;
        UIInternal.nextTick(function () {
            var _a;
            var toValidate = {
                object: _this.currentRecord
            };
            if (((_a = _this.column.validatePropertyName) === null || _a === void 0 ? void 0 : _a.length) > 0) {
                Object.assign(toValidate, { propertyName: _this.column.validatePropertyName });
            }
            _this.validationController.validate(toValidate);
        });
    };
    BodyCell.prototype.compileCell = function (el, newVersion) {
        var _a, _b;
        if (newVersion === void 0) { newVersion = false; }
        if (this.currentRecord == null) {
            if (this.render) {
                this.render(this);
            }
            return;
        }
        if (!newVersion) {
            this.cleanUp();
        }
        if (this.cellDisabled != null && this.column instanceof UIColumn && this.column.type == 'checkbox') {
            this.currentRecord.cellDisabled = this.cellDisabled(this.currentRecord);
        }
        if (el) {
            if (this.column instanceof UITableAction) {
                this.compileActions();
            }
            if (this.column.templateCell == null)
                throw new Error("Template cell is missing");
            var tpl = this.column.templateCell.outerHTML;
            if (((_b = (_a = this.overrideContext.parentOverrideContext) === null || _a === void 0 ? void 0 : _a.parentOverrideContext) === null || _b === void 0 ? void 0 : _b.__parentOverrideContext) != null) {
                if (!newVersion || !this.isRendered) {
                    this.column.compileCell();
                    this.view = this.column.view;
                    this.slot.add(this.column.view);
                }
                else {
                    this.slot.unbind();
                }
                this.slot.bind(this, createOverrideContext(this.currentRecord, this.overrideContext.parentOverrideContext.parentOverrideContext.__parentOverrideContext));
                if (!newVersion || !this.isRendered) {
                    this.slot.attached();
                }
                if (this.render) {
                    this.render(this);
                }
                if (this.focusData != null && this.focusData.colIndex == this.colIndex && this.focusData.data == this.currentRecord) {
                    var input = this.slot.anchor.querySelector('input');
                    if (input != null) {
                        input.focus();
                    }
                }
                this.isRendered = true;
            }
        }
        this.setTitle();
        return;
    };
    BodyCell.prototype.setActiveField = function () {
        if (this.isRendered === false) {
            return;
        }
        this.focusData = { data: this.currentRecord, colIndex: this.colIndex };
    };
    BodyCell.prototype.cleanUp = function () {
        if (this.isRendered === true) {
            try {
                this.slot.detached();
            }
            catch (e) { }
            try {
                this.slot.unbind();
            }
            catch (e) { }
            try {
                this.slot.removeAll();
            }
            catch (e) { }
            this.isRendered = false;
        }
    };
    BodyCell.prototype.compileActions = function () {
        var _a;
        this.menuItemsBodyCell.splice(0);
        (_a = this.menuItemsBodyCell).push.apply(_a, __spreadArray([], __read(this.column.compileTemplate(this.currentRecord)), false));
    };
    BodyCell.prototype.processCurrentRecord = function () {
        var _a, _b, _c, _d, _e, _f;
        return __awaiter(this, void 0, void 0, function () {
            var _g;
            var _this = this;
            return __generator(this, function (_h) {
                switch (_h.label) {
                    case 0:
                        if (!(this.currentRecord != null)) return [3, 6];
                        if (!isFunction(this.rowRoute)) return [3, 4];
                        if (!((_c = (_b = (_a = this.currentRecord.entityAspect) === null || _a === void 0 ? void 0 : _a.entityState) === null || _b === void 0 ? void 0 : _b.isAdded()) !== null && _c !== void 0 ? _c : false)) return [3, 1];
                        this.hasChangesSubscriptionKey = (_d = this.currentRecord.entityAspect.propertyChanged) === null || _d === void 0 ? void 0 : _d.subscribe(function (data) { return __awaiter(_this, void 0, void 0, function () {
                            var _a;
                            var _b;
                            return __generator(this, function (_c) {
                                switch (_c.label) {
                                    case 0:
                                        if (!(data.propertyName == "id")) return [3, 2];
                                        _a = this;
                                        return [4, this.rowRoute({ record: this.currentRecord })];
                                    case 1:
                                        _a.route = _c.sent();
                                        (_b = this.currentRecord.entityAspect.propertyChanged) === null || _b === void 0 ? void 0 : _b.unsubscribe(this.hasChangesSubscriptionKey);
                                        this.hasChangesSubscriptionKey = null;
                                        _c.label = 2;
                                    case 2:
                                        if (data.propertyName != null) {
                                            this.signaler.signal('refresh_cell');
                                        }
                                        return [2];
                                }
                            });
                        }); });
                        return [3, 3];
                    case 1:
                        _g = this;
                        return [4, this.rowRoute({ record: this.currentRecord })];
                    case 2:
                        _g.route = _h.sent();
                        _h.label = 3;
                    case 3: return [3, 5];
                    case 4:
                        this.route = this.rowRoute;
                        _h.label = 5;
                    case 5:
                        (_f = (_e = this.currentRecord.entityAspect) === null || _e === void 0 ? void 0 : _e.propertyChanged) === null || _f === void 0 ? void 0 : _f.subscribe(function (data) {
                            if (data.propertyName != null) {
                                _this.signaler.signal('refresh_cell');
                            }
                        });
                        _h.label = 6;
                    case 6: return [2];
                }
            });
        });
    };
    BodyCell.prototype.cellDisabled = function (record) {
        return this.onCellSelected != null ? this.onCellSelected({ record: record }) == false : false;
    };
    __decorate([
        bindable({ defaultBindingMode: bindingMode.toView }),
        __metadata("design:type", Object)
    ], BodyCell.prototype, "column", void 0);
    __decorate([
        bindable({ defaultBindingMode: bindingMode.toView }),
        __metadata("design:type", Number)
    ], BodyCell.prototype, "indexDrag", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Function)
    ], BodyCell.prototype, "onCellClicked", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Object)
    ], BodyCell.prototype, "rowRoute", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Object)
    ], BodyCell.prototype, "currentRecord", void 0);
    __decorate([
        bindable,
        __metadata("design:type", Function)
    ], BodyCell.prototype, "render", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Number)
    ], BodyCell.prototype, "tableAuTargetId", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Number)
    ], BodyCell.prototype, "colIndex", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Object)
    ], BodyCell.prototype, "focusData", void 0);
    __decorate([
        bindable,
        __metadata("design:type", Number)
    ], BodyCell.prototype, "rowIndex", void 0);
    __decorate([
        bindable(),
        __metadata("design:type", Function)
    ], BodyCell.prototype, "onCellSelected", void 0);
    __decorate([
        observable,
        __metadata("design:type", String)
    ], BodyCell.prototype, "route", void 0);
    __decorate([
        computedFrom("route", "onCellClicked", "column.isRowClickIgnore"),
        __metadata("design:type", Boolean),
        __metadata("design:paramtypes", [])
    ], BodyCell.prototype, "isClickable", null);
    __decorate([
        computedFrom("_title"),
        __metadata("design:type", Object),
        __metadata("design:paramtypes", [])
    ], BodyCell.prototype, "title", null);
    BodyCell = __decorate([
        containerless(),
        autoinject(),
        processContent(function (compiler, resources, node, instruction) {
            instruction.inheritBindingContext = true;
            return true;
        }),
        __metadata("design:paramtypes", [Router, BindingSignaler, ValidationController, BindingEngine])
    ], BodyCell);
    return BodyCell;
}());

//# sourceMappingURL=body-cell.js.map
