"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 };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.UIEnumerationSelect = void 0;
var aurelia_framework_1 = require("aurelia-framework");
var aurelia_binding_1 = require("aurelia-binding");
var aurelia_templating_1 = require("aurelia-templating");
var editing_mode_enum_1 = require("./../../vm/editing-mode-enum");
var enumeration_type_service_1 = require("./../../services/enumeration-type-service");
var box_1 = require("./../../modules/box");
var common_model_1 = require("./../../model/common-model");
var enumeration_type_detail_1 = require("./../../vm/enumeration-types/enumeration-type-detail");
var aurelia_i18n_1 = require("aurelia-i18n");
var config_1 = require("./../../config");
var breeze_client_1 = require("breeze-client");
var UIEnumerationSelect = exports.UIEnumerationSelect = (function () {
    function UIEnumerationSelect(element, parser, bindingEngine, box, i18n, config) {
        this.element = element;
        this.parser = parser;
        this.bindingEngine = bindingEngine;
        this.box = box;
        this.i18n = i18n;
        this.config = config;
        this.isCreation = null;
        this.disabled = false;
        this.showTag = true;
        this.readonly = false;
        this.hasForeignKeyLink = true;
        this.canCreate = false;
        this.disabled = element.hasAttribute("disabled");
    }
    UIEnumerationSelect.prototype.bind = function (bindingContext, overrideContext) {
        var _this = this;
        var _a, _b, _c, _d, _e, _f;
        if (this.enumerationTypeService == null) {
            this.enumerationTypeService = new enumeration_type_service_1.EnumerationTypeService(this.enumerationCategory);
        }
        var enumerationTypeCategory = (_a = this.config.enumerationTypeConfig.enumerationTypeCategories) === null || _a === void 0 ? void 0 : _a.find(function (x) { return x.category == _this.enumerationCategory; });
        (_b = this.createDialogLabelTr) !== null && _b !== void 0 ? _b : (this.createDialogLabelTr = (_c = enumerationTypeCategory === null || enumerationTypeCategory === void 0 ? void 0 : enumerationTypeCategory.name) !== null && _c !== void 0 ? _c : "common:enumerationtype.addEnumerationtype");
        (_d = this.createButtonLabelTr) !== null && _d !== void 0 ? _d : (this.createButtonLabelTr = (_e = enumerationTypeCategory === null || enumerationTypeCategory === void 0 ? void 0 : enumerationTypeCategory.addName) !== null && _e !== void 0 ? _e : "common:enumerationtype.addEnumerationtype");
        if (this.isCreation == null && bindingContext != null) {
            this.isCreation = bindingContext.editingMode == editing_mode_enum_1.EditingModeEnum.Create;
        }
        if (((_f = this.value) === null || _f === void 0 ? void 0 : _f.length) > 0) {
            var values = this.value.split('.');
            if (values.length > 1) {
                this.propertyName = values.pop();
                var entityName = values.join('.');
                var entityObserver = this.bindingEngine.expressionObserver(bindingContext, entityName);
                this.entityObserverDispsable = entityObserver.subscribe(function (n, o) { return _this.entityChanged(n, o); });
                var valueExpression = this.parser.parse(entityName);
                var scope = {
                    bindingContext: bindingContext,
                    overrideContext: overrideContext
                };
                var entity = valueExpression.evaluate(scope);
                if (entity != null) {
                    this.entityChanged(entity, null);
                }
            }
            else if (values.length == 1) {
                this.propertyName = this.value;
                this.entityChanged(bindingContext, null);
            }
        }
    };
    UIEnumerationSelect.prototype.entityChanged = function (n, o) {
        var _this = this;
        var _a;
        this.entity = n;
        if (!this.hasForeignKeyLink) {
            this.propertyId = this.propertyName + "Id";
        }
        else if (this.entity != null && (this.propertyId == null || this.isRequired == null)) {
            var navProp = this.entity.entityType.navigationProperties.find(function (fkp) { return fkp.name == _this.propertyName; });
            if (((_a = navProp === null || navProp === void 0 ? void 0 : navProp.relatedDataProperties) === null || _a === void 0 ? void 0 : _a.length) > 0) {
                var dataProp = navProp.relatedDataProperties[0];
                if (this.propertyId == null) {
                    this.propertyId = dataProp.name;
                }
                if (this.isRequired == null) {
                    this.isRequired = !dataProp.isNullable;
                }
            }
        }
        this.initValue(!this.hasForeignKeyLink);
    };
    UIEnumerationSelect.prototype.detached = function () {
        var _a;
        (_a = this.entityObserverDispsable) === null || _a === void 0 ? void 0 : _a.dispose();
    };
    UIEnumerationSelect.prototype.isRequiredChanged = function () {
        this.initValue();
    };
    UIEnumerationSelect.prototype.isCreationChanged = function () {
        this.initValue();
    };
    UIEnumerationSelect.prototype.initValue = function (setFk) {
        if (setFk === void 0) { setFk = false; }
        return __awaiter(this, void 0, void 0, function () {
            var _a, _b, _c, _d, _e;
            return __generator(this, function (_f) {
                switch (_f.label) {
                    case 0:
                        if (!(this.entity != null && this.propertyName != null && this.propertyId != null)) return [3, 6];
                        if (!(this.entity[this.propertyId] == null && this.entity[this.propertyName] == null && this.isCreation)) return [3, 5];
                        _a = this.entity;
                        _b = this.propertyName;
                        return [4, this.enumerationTypeService.getDefault()];
                    case 1:
                        _a[_b] = _f.sent();
                        _c = this.isRequired && this.entity[this.propertyName] == null;
                        if (!_c) return [3, 3];
                        return [4, this.enumerationTypeService.getCount()];
                    case 2:
                        _c = (_f.sent()) == 1;
                        _f.label = 3;
                    case 3:
                        if (!_c) return [3, 5];
                        _d = this.entity;
                        _e = this.propertyName;
                        return [4, this.enumerationTypeService.getFirst()];
                    case 4:
                        _d[_e] = _f.sent();
                        _f.label = 5;
                    case 5:
                        if (setFk && this.entity[this.propertyName] != null) {
                            this.entity[this.propertyId] = this.entity[this.propertyName].id;
                        }
                        _f.label = 6;
                    case 6: return [2];
                }
            });
        });
    };
    UIEnumerationSelect.prototype.creationFunction = function () {
        var _this = this;
        if (this.createFn) {
            this.createFn();
        }
        else {
            this.box.showEditDialog(enumeration_type_detail_1.EnumerationTypeDetail, common_model_1.Various.NewId, this.i18n.tr(this.createDialogLabelTr), { model: { param2: this.enumerationCategory } })
                .whenClosed(function (result) {
                if (!result.wasCancelled && result.output) {
                    _this.entity[_this.propertyName] = result.output;
                }
            });
        }
    };
    UIEnumerationSelect.prototype.onChange = function (value) {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            var _b, _c;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        if (!(value != null && ((_a = this.entity[this.propertyName]) === null || _a === void 0 ? void 0 : _a.id) != value)) return [3, 2];
                        _b = this.entity;
                        _c = this.propertyName;
                        return [4, this.enumerationTypeService.firstEntity(new breeze_client_1.Predicate("id", breeze_client_1.FilterQueryOp.Equals, value))];
                    case 1:
                        _b[_c] = _d.sent();
                        _d.label = 2;
                    case 2: return [2];
                }
            });
        });
    };
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_binding_1.bindingMode.twoWay }),
        __metadata("design:type", String)
    ], UIEnumerationSelect.prototype, "value", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_binding_1.bindingMode.oneTime }),
        __metadata("design:type", Number)
    ], UIEnumerationSelect.prototype, "enumerationCategory", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_binding_1.bindingMode.toView }),
        __metadata("design:type", Boolean)
    ], UIEnumerationSelect.prototype, "isRequired", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_binding_1.bindingMode.oneTime }),
        __metadata("design:type", String)
    ], UIEnumerationSelect.prototype, "sortColumn", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_binding_1.bindingMode.oneTime }),
        __metadata("design:type", String)
    ], UIEnumerationSelect.prototype, "propertyId", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_binding_1.bindingMode.toView }),
        __metadata("design:type", Boolean)
    ], UIEnumerationSelect.prototype, "isCreation", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_binding_1.bindingMode.toView }),
        __metadata("design:type", Boolean)
    ], UIEnumerationSelect.prototype, "disabled", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_binding_1.bindingMode.toView }),
        __metadata("design:type", Boolean)
    ], UIEnumerationSelect.prototype, "showTag", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_binding_1.bindingMode.toView }),
        __metadata("design:type", Boolean)
    ], UIEnumerationSelect.prototype, "readonly", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_binding_1.bindingMode.toView }),
        __metadata("design:type", enumeration_type_service_1.EnumerationTypeService)
    ], UIEnumerationSelect.prototype, "enumerationTypeService", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_binding_1.bindingMode.toView }),
        __metadata("design:type", String)
    ], UIEnumerationSelect.prototype, "placeholder", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_binding_1.bindingMode.toView }),
        __metadata("design:type", Boolean)
    ], UIEnumerationSelect.prototype, "hasForeignKeyLink", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_binding_1.bindingMode.toView }),
        __metadata("design:type", Boolean)
    ], UIEnumerationSelect.prototype, "canCreate", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_binding_1.bindingMode.toView }),
        __metadata("design:type", Function)
    ], UIEnumerationSelect.prototype, "createFn", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_binding_1.bindingMode.toView }),
        __metadata("design:type", String)
    ], UIEnumerationSelect.prototype, "createButtonLabelTr", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_binding_1.bindingMode.toView }),
        __metadata("design:type", String)
    ], UIEnumerationSelect.prototype, "createDialogLabelTr", void 0);
    UIEnumerationSelect = __decorate([
        (0, aurelia_templating_1.customElement)('ui-enumeration-select'),
        __metadata("design:paramtypes", [Element, aurelia_binding_1.Parser, aurelia_framework_1.BindingEngine, box_1.Box, aurelia_i18n_1.I18N, config_1.Config])
    ], UIEnumerationSelect);
    return UIEnumerationSelect;
}());

//# sourceMappingURL=ui-enumeration-select.js.map
