"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 __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));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.UITreePanel = void 0;
var ui_tree_panel_config_1 = require("./ui-tree-panel-config");
var aurelia_i18n_1 = require("aurelia-i18n");
var aurelia_framework_1 = require("aurelia-framework");
var ui_tree_model_1 = require("../ui-tree-model");
var ui_internal_1 = require("../../../utils/ui-internal");
var aurelia_binding_1 = require("aurelia-binding");
var UITreePanel = exports.UITreePanel = (function () {
    function UITreePanel(element, bindingEngine, i18n) {
        this.element = element;
        this.bindingEngine = bindingEngine;
        this.i18n = i18n;
        this.treeOptions = [];
        this.singleLineHeader = true;
        this.showCollapseAll = false;
        this.showNodeExpand = true;
        this.labelSearch = this.i18n.tr('treepanel.search', { ns: 'common' });
        this.labelDeselectAll = this.i18n.tr('treepanel.deselectAll', { ns: 'common' });
        this.labelEmpty = this.i18n.tr('treepanel.empty', { ns: 'common' });
        this.labelLess = this.i18n.tr('treepanel.less', { ns: 'common' });
        this.labelMore = this.i18n.tr('treepanel.more', { ns: 'common' });
        this.checkable = false;
        this.searchable = false;
        this.canRefresh = false;
        this.autoCheckable = true;
        this.checkableWhenEmpty = false;
        this.autoSort = true;
        this.checkable = element.hasAttribute("checkable");
        this.searchable = element.hasAttribute("searchable");
    }
    UITreePanel.prototype.select = function (node, event) {
        var _this = this;
        if (event === void 0) { event = null; }
        if (false == node.isSelectable) {
            return;
        }
        if (this.checkable !== false) {
            if (typeof this.checkable == 'number' && node.level >= this.checkable) {
                if (this.maxValues != null && this.rootNode.nodes.filter(function (x) { return x.checked; }).length == this.maxValues) {
                    this.internalToggleCheck(this.rootNode.nodes.filter(function (x) { return x.checked && _this.value[0] == x.id; })[0], true);
                }
                this.toggleCheck(node, event);
                this.getCheckedValues();
                this.element.dispatchEvent(ui_internal_1.UIInternal.createEvent("checked", this.value));
            }
        }
        else {
            return ui_internal_1.UIInternal.fireCallbackEvent(this, "beforeselect").then(function (b) {
                return b ? _this.changeSelection(node) : false;
            });
        }
    };
    UITreePanel.prototype.bind = function () {
        var _this = this;
        this.parseOptionsAsTree();
        this.selectOptionsFromValue(this.treeOptions);
        this.rootNode = new ui_tree_model_1.UITreeModel(this.treeOptions, this.maxNodes, this.autoCheckable, this.autoSort);
        this.disposable = this.bindingEngine.collectionObserver(this.options).subscribe(function () { return _this.optionsChanged(); });
        this.valueDisposable = this.bindingEngine.collectionObserver(this.value).subscribe(function () { return _this.valueChanged(); });
    };
    UITreePanel.prototype.optionsChanged = function () {
        var _a;
        this.parseOptionsAsTree();
        this.rootNode = new ui_tree_model_1.UITreeModel(this.treeOptions, this.maxNodes, this.autoCheckable, this.autoSort);
        if (((_a = this.searchText) === null || _a === void 0 ? void 0 : _a.length) > 0) {
            this.searchTextChanged(this.searchText);
        }
    };
    UITreePanel.prototype.valueChanged = function () {
        this.selectOptionsFromValue(this.treeOptions);
    };
    UITreePanel.prototype.refreshSelectedTreeValues = function () {
        var _a;
        this.value.splice(0);
        (_a = this.rootNode) === null || _a === void 0 ? void 0 : _a.nodes.forEach(function (node) {
            node.checked = 0;
        });
    };
    UITreePanel.prototype.selectOptionsFromValue = function (options) {
        var _this = this;
        var _a;
        if (((_a = this.value) === null || _a === void 0 ? void 0 : _a.length) > 0) {
            options.forEach(function (option) {
                var _a;
                if (option.id) {
                    option.selected = _this.value.indexOf(option.id) > -1;
                    if (option.selected) {
                        (_a = _this.rootNode) === null || _a === void 0 ? void 0 : _a.expandNode(option.id);
                    }
                }
                if (option.children) {
                    _this.selectOptionsFromValue(option.children);
                }
            });
        }
    };
    UITreePanel.prototype.unbind = function () {
        if (this.disposable)
            this.disposable.dispose();
        if (this.valueDisposable)
            this.valueDisposable.dispose();
    };
    UITreePanel.prototype.toggleExpand = function (index) {
        var _a;
        (_a = this.rootNode) === null || _a === void 0 ? void 0 : _a.toggleExpand(index);
    };
    UITreePanel.prototype.toggleMore = function (index) {
        var _a;
        (_a = this.rootNode) === null || _a === void 0 ? void 0 : _a.toggleMore(index);
    };
    UITreePanel.prototype.toggleCheck = function (node, event) {
        var _this = this;
        if (event.shiftKey === false) {
            this.internalToggleCheck(node, true);
        }
        else {
            if (!this.lastCheck) {
                this.internalToggleCheck(node, true);
            }
            else {
                var lastCheckNodeIndex = this.rootNode.nodes.findIndex(function (n) { return n.id == _this.lastCheck.id; });
                var currentCheckNodeIndex = this.rootNode.nodes.indexOf(node);
                if (lastCheckNodeIndex > -1 && currentCheckNodeIndex > -1) {
                    if (currentCheckNodeIndex > lastCheckNodeIndex) {
                        for (var index = lastCheckNodeIndex + 1; index <= currentCheckNodeIndex; index++) {
                            var node_1 = this.rootNode.nodes[index];
                            this.internalToggleCheck(node_1, true);
                        }
                    }
                    else {
                        for (var index = lastCheckNodeIndex - 1; index >= currentCheckNodeIndex; index--) {
                            var node_2 = this.rootNode.nodes[index];
                            this.internalToggleCheck(node_2, true);
                        }
                    }
                }
                else {
                    this.internalToggleCheck(node, true);
                }
            }
        }
    };
    UITreePanel.prototype.internalToggleCheck = function (node, isInitial) {
        if (isInitial === void 0) { isInitial = true; }
        if (isInitial) {
            node.toggleCheck(true, this.autoCheckable);
        }
        this.lastCheck = node;
    };
    UITreePanel.prototype.getCheckedValues = function () {
        var _this = this;
        var _a;
        if (!this.value)
            this.value = [];
        if (!this.model)
            this.model = [];
        (_a = this.rootNode) === null || _a === void 0 ? void 0 : _a.nodes.forEach(function (node) {
            if (node.checked == 1) {
                if (node.id) {
                    if (_this.value.indexOf(node.id) < 0)
                        _this.value.push(node.id);
                }
                if (node.model) {
                    if (_this.model.indexOf(node.model) < 0)
                        _this.model.push(node.model);
                }
            }
            else {
                if (node.id) {
                    _this.value.remove(node.id);
                }
                if (node.model) {
                    _this.model.remove(node.model);
                }
            }
        });
    };
    UITreePanel.prototype.searchTextChanged = function (query) {
        var _a;
        (_a = this.rootNode) === null || _a === void 0 ? void 0 : _a.filter(query);
    };
    UITreePanel.prototype.changeSelection = function (node) {
        this.value = [node.id];
        this.model = [node.model];
        this.element.dispatchEvent(ui_internal_1.UIInternal.createEvent("select", node.id));
    };
    UITreePanel.prototype.parseOptionsAsTree = function () {
        var _a;
        var _b;
        var actions = [];
        if (Array.isArray((_b = this.treeConfig) === null || _b === void 0 ? void 0 : _b.actions) && this.treeConfig.actions.length > 0) {
            actions = this.treeConfig.actions.map(function (action) { return action.transformToTreeAction(); });
        }
        var options = this.treeConfig ? this.getChildren(null, 0, actions) : this.options;
        (_a = this.treeOptions).splice.apply(_a, __spreadArray([0, this.treeOptions.length], __read(options), false));
    };
    UITreePanel.prototype.getChildren = function (id, level, actions) {
        var _this = this;
        var nodes = [];
        var defaultExpanded = true;
        if (this.treeConfig) {
            defaultExpanded = isNumber(this.treeConfig.autoExpand) ? level < this.treeConfig.autoExpand : this.treeConfig.autoExpand;
        }
        this.options.filter(function (entry) { return entry[_this.treeConfig.parentId] == id; }).forEach(function (entry) {
            var _a;
            var id = entry[_this.treeConfig.id];
            var children = _this.getChildren(id, level + 1, actions);
            var uiTreeNode = new ui_tree_model_1.UITreeNode({
                id: id,
                label: typeof _this.treeConfig.label === 'string' ? entry[_this.treeConfig.label] : _this.treeConfig.label(entry),
                icon: _this.treeConfig.icon == null ? null : entry[_this.treeConfig.icon],
                model: entry,
                expanded: false,
                isSelectable: _this.treeConfig.isNodeSelectable ? _this.treeConfig.isNodeSelectable(entry) : true,
                isExpandable: _this.treeConfig.isNodeExpandable ? _this.treeConfig.isNodeExpandable(entry) : true,
                selected: (_this.value || []).find(function (v) { return v == id; }) != null,
                leaf: children.length === 0,
                children: children,
            }).assignActions(actions);
            if (uiTreeNode.hasSelectedChild()) {
                uiTreeNode.expanded = true;
            }
            else {
                var existing = _this.findNodeInStructure(id, (_a = _this.rootNode) === null || _a === void 0 ? void 0 : _a.children);
                uiTreeNode.expanded = existing ? existing.expanded : defaultExpanded;
            }
            nodes.push(uiTreeNode);
        }, []);
        return nodes;
    };
    UITreePanel.prototype.findNodeInStructure = function (id, nodes) {
        var _this = this;
        return nodes === null || nodes === void 0 ? void 0 : nodes.reduce(function (found, node) {
            if (found != null) {
                return found;
            }
            else if (node.id == id) {
                return node;
            }
            else {
                return _this.findNodeInStructure(id, node.children);
            }
        }, null);
    };
    Object.defineProperty(UITreePanel.prototype, "showExpandAll", {
        get: function () {
            var _a;
            return null != (((_a = this.rootNode) === null || _a === void 0 ? void 0 : _a.nodes) || []).find(function (node) {
                return node.leaf == false && node.expanded == false;
            });
        },
        enumerable: false,
        configurable: true
    });
    UITreePanel.prototype.toggleExpandAll = function () {
        if (this.rootNode) {
            var expanded = this.showExpandAll;
            for (var i = 0; i < this.rootNode.nodes.length; ++i) {
                if (this.rootNode.nodes[i].leaf == false && this.rootNode.nodes[i].expanded != expanded) {
                    this.toggleExpand(i);
                }
            }
        }
    };
    Object.defineProperty(UITreePanel.prototype, "showExportCsv", {
        get: function () {
            return this.exportToCsv != null;
        },
        enumerable: false,
        configurable: true
    });
    __decorate([
        (0, aurelia_framework_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.twoWay }),
        __metadata("design:type", Object)
    ], UITreePanel.prototype, "value", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.twoWay }),
        __metadata("design:type", Object)
    ], UITreePanel.prototype, "model", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.toView }),
        __metadata("design:type", Array)
    ], UITreePanel.prototype, "options", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.toView }),
        __metadata("design:type", ui_tree_panel_config_1.UITreePanelConfig)
    ], UITreePanel.prototype, "treeConfig", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.toView }),
        __metadata("design:type", Boolean)
    ], UITreePanel.prototype, "singleLineHeader", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.toView }),
        __metadata("design:type", Boolean)
    ], UITreePanel.prototype, "showCollapseAll", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", Boolean)
    ], UITreePanel.prototype, "showNodeExpand", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", String)
    ], UITreePanel.prototype, "labelSearch", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", String)
    ], UITreePanel.prototype, "labelDeselectAll", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", String)
    ], UITreePanel.prototype, "labelEmpty", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", String)
    ], UITreePanel.prototype, "labelLess", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", String)
    ], UITreePanel.prototype, "labelMore", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Number)
    ], UITreePanel.prototype, "maxNodes", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Object)
    ], UITreePanel.prototype, "checkable", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Boolean)
    ], UITreePanel.prototype, "searchable", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Boolean)
    ], UITreePanel.prototype, "canRefresh", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Boolean)
    ], UITreePanel.prototype, "autoCheckable", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Boolean)
    ], UITreePanel.prototype, "checkableWhenEmpty", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)(),
        __metadata("design:type", Number)
    ], UITreePanel.prototype, "maxValues", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.oneTime }),
        __metadata("design:type", Function)
    ], UITreePanel.prototype, "exportToCsv", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.oneTime }),
        __metadata("design:type", Object)
    ], UITreePanel.prototype, "autoSort", void 0);
    UITreePanel = __decorate([
        (0, aurelia_framework_1.customElement)("ui-tree-panel"),
        (0, aurelia_framework_1.inject)(Element, aurelia_binding_1.BindingEngine, aurelia_i18n_1.I18N),
        __metadata("design:paramtypes", [Element, aurelia_binding_1.BindingEngine, aurelia_i18n_1.I18N])
    ], UITreePanel);
    return UITreePanel;
}());

//# sourceMappingURL=ui-tree-panel.js.map
