var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
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 };
    }
};
import { UtilsMlFieldHelper } from './../../utils/utils-ml-field-helper';
import { Router } from 'aurelia-router';
import { EnumerationTypeService } from './../../services/enumeration-type-service';
import { I18N } from 'aurelia-i18n';
import { autoinject, BindingEngine, computedFrom, observable } from "aurelia-framework";
import { FilterQueryOp, Predicate } from "breeze-client";
import { ServiceBase } from "../../data/service-base";
import { Various } from "../../model/common-model";
import { CustomLogger } from "../../modules/custom-logger";
import { EnumerationTypeColorRessourceName, EnumerationTypeRessourceName } from "../../utils/enumeration-types-helper";
import { validateEnumerationType } from "../../utils/enumeration-types-helper";
import { EntityDetailViewModelBase } from "../detail-view-model-base";
import { EditingModeEnum } from "../editing-mode-enum";
export var EnumerationTypeDetailViewModelBase = (function (_super) {
    __extends(EnumerationTypeDetailViewModelBase, _super);
    function EnumerationTypeDetailViewModelBase(router, logger, i18n, bindingEngine, skipMandatoryLanguageForDBInfo) {
        if (skipMandatoryLanguageForDBInfo === void 0) { skipMandatoryLanguageForDBInfo = false; }
        var _this = _super.call(this, router, logger) || this;
        _this.bindingEngine = bindingEngine;
        _this.skipMandatoryLanguageForDBInfo = skipMandatoryLanguageForDBInfo;
        _this.ressourceName = EnumerationTypeRessourceName;
        _this.showOrder = false;
        _this.hasClosedEntry = false;
        _super.prototype.initialize.call(_this, new ServiceBase(EnumerationTypeRessourceName));
        _this._enumerationTypeColorService = new ServiceBase(EnumerationTypeColorRessourceName);
        _this.showOrder = _this.config.enumerationTypeConfig.useOrder;
        _this._enumerationTypesEnum = _this.config.enumerationTypeConfig.enumerationTypes;
        return _this;
    }
    Object.defineProperty(EnumerationTypeDetailViewModelBase.prototype, "isClosedEntry", {
        get: function () {
            var _a;
            return !((_a = this.entity) === null || _a === void 0 ? void 0 : _a.isEditable);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EnumerationTypeDetailViewModelBase.prototype, "enumerationTypeColorService", {
        get: function () {
            return this._enumerationTypeColorService;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EnumerationTypeDetailViewModelBase.prototype, "enumerationTypesEnum", {
        get: function () {
            return this._enumerationTypesEnum;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EnumerationTypeDetailViewModelBase.prototype, "category", {
        get: function () {
            return this._category;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EnumerationTypeDetailViewModelBase.prototype, "enumerationTypeConfig", {
        get: function () {
            var _this = this;
            var _a;
            return (_a = this.config.enumerationTypeConfig.enumerationTypeCategories) === null || _a === void 0 ? void 0 : _a.find(function (t) { return t.category == _this.category; });
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EnumerationTypeDetailViewModelBase.prototype, "ribbonHeaderText", {
        get: function () {
            if (this.enumerationTypesEnum) {
                return "enumerationtype." + this.setFirstLetterToLowerCase(this.enumerationTypesEnum[this.category].toString());
            }
            return "enumerationtype.enumerationtype";
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EnumerationTypeDetailViewModelBase.prototype, "documentTitle", {
        get: function () {
            var _a, _b;
            if (this.editingMode === EditingModeEnum.Create) {
                if (this.enumerationTypesEnum) {
                    return this.i18n.tr("enumerationtype." + this.setFirstLetterToLowerCase(this.enumerationTypesEnum[this.category].toString()));
                }
                else {
                    return this.i18n.tr("enumerationtype.enumerationtype");
                }
            }
            else if (this.entity) {
                return (_b = (_a = this.entity) === null || _a === void 0 ? void 0 : _a.denomination) === null || _b === void 0 ? void 0 : _b._translation;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EnumerationTypeDetailViewModelBase.prototype, "isUniqueCodeRequired", {
        get: function () {
            return this.config.enumerationTypeConfig.isUniqueCodeRequired;
        },
        enumerable: false,
        configurable: true
    });
    EnumerationTypeDetailViewModelBase.prototype.setFirstLetterToLowerCase = function (a) {
        return (a + '').charAt(0).toLowerCase() + a.substring(1);
    };
    EnumerationTypeDetailViewModelBase.prototype.activate = function (params) {
        return __awaiter(this, void 0, void 0, function () {
            var id, _a, _b, _c, applicationParameters;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        id = params.param1;
                        this._category = params.param2;
                        _super.prototype.initialize.call(this, new EnumerationTypeService(this.category));
                        _a = this;
                        return [4, this.service.getCount(new Predicate('isEditable', FilterQueryOp.Equals, false))];
                    case 1:
                        _a.hasClosedEntry = (_d.sent()) > 0;
                        if (!(id == Various.NewId)) return [3, 3];
                        this.editingMode = EditingModeEnum.Create;
                        _b = this;
                        return [4, this.service.createEntity({ isEditable: true })];
                    case 2:
                        _b.entity = _d.sent();
                        if (params.callback != null) {
                            params.callback(this.entity);
                        }
                        return [3, 5];
                    case 3:
                        this.editingMode = EditingModeEnum.Update;
                        _c = this;
                        return [4, this.service.getEntityById(id)];
                    case 4:
                        _c.entity = _d.sent();
                        this.controller.addObject(this.entity);
                        _d.label = 5;
                    case 5:
                        if (!(this.applicationParametersService != null && false == this.skipMandatoryLanguageForDBInfo)) return [3, 7];
                        return [4, this.applicationParametersService.firstEntity(null, ['mandatoryLanguageForDBInfo'])];
                    case 6:
                        applicationParameters = _d.sent();
                        if (applicationParameters != null && applicationParameters.mandatoryLanguageForDBInfo != null) {
                            this.selectedLanguageCode = applicationParameters.mandatoryLanguageForDBInfo.uniqueCode.toLowerCase();
                        }
                        _d.label = 7;
                    case 7:
                        _super.prototype.activate.call(this, params);
                        validateEnumerationType(this.entity, this.isUniqueCodeRequired);
                        return [2];
                }
            });
        });
    };
    EnumerationTypeDetailViewModelBase.prototype.cancel = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.enumerationTypeColor = { id: null, text: null };
                        return [4, _super.prototype.cancel.call(this)];
                    case 1:
                        _a.sent();
                        return [2];
                }
            });
        });
    };
    EnumerationTypeDetailViewModelBase.prototype.attached = function () {
        var _this = this;
        this.disposables.push(this.bindingEngine.propertyObserver(this, 'enumerationTypeColor').subscribe(function (newValue) { return __awaiter(_this, void 0, void 0, function () {
            var enumerationTypeColor;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (newValue == null || isNaN(newValue)) {
                            return [2];
                        }
                        return [4, this.enumerationTypeColorService.firstEntity(new Predicate("id", FilterQueryOp.Equals, newValue))];
                    case 1:
                        enumerationTypeColor = _a.sent();
                        this.entity.textColor = enumerationTypeColor.textColor;
                        this.entity.backgroundColor = enumerationTypeColor.backgroundColor;
                        return [2];
                }
            });
        }); }));
    };
    EnumerationTypeDetailViewModelBase.prototype.activeChanged = function () {
        this.entity.default = this.entity.default && this.entity.active;
    };
    Object.defineProperty(EnumerationTypeDetailViewModelBase.prototype, "tagLabel", {
        get: function () {
            var _this = this;
            var _a;
            if (this.selectedLanguageCode) {
                var language = (_a = this.config.globalConfig.configuredLanguages) === null || _a === void 0 ? void 0 : _a.find(function (l) { return l.code == _this.selectedLanguageCode; });
                if (language) {
                    return this.entity.denomination['lang' + language.columnIndex];
                }
            }
            return '';
        },
        enumerable: false,
        configurable: true
    });
    EnumerationTypeDetailViewModelBase.prototype.beforeSave = function () {
        return __awaiter(this, void 0, void 0, function () {
            var mlInputBeforeSave, _a, _b;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        _a = false == this.config.enumerationTypeConfig.completeTranslatedFields;
                        if (_a) return [3, 2];
                        return [4, UtilsMlFieldHelper.BeforeSave(this.entity, [
                                { prop: this.entity.denomination, label: 'enumerationtype.denomination', isRequired: true }
                            ])];
                    case 1:
                        _a = (_c.sent());
                        _c.label = 2;
                    case 2:
                        mlInputBeforeSave = _a;
                        _b = mlInputBeforeSave;
                        if (!_b) return [3, 4];
                        return [4, _super.prototype.beforeSave.call(this)];
                    case 3:
                        _b = (_c.sent());
                        _c.label = 4;
                    case 4: return [2, _b];
                }
            });
        });
    };
    __decorate([
        observable,
        __metadata("design:type", Object)
    ], EnumerationTypeDetailViewModelBase.prototype, "enumerationTypeColor", void 0);
    __decorate([
        computedFrom('entity.isEditable'),
        __metadata("design:type", Boolean),
        __metadata("design:paramtypes", [])
    ], EnumerationTypeDetailViewModelBase.prototype, "isClosedEntry", null);
    __decorate([
        computedFrom('_enumerationTypeColorService'),
        __metadata("design:type", ServiceBase),
        __metadata("design:paramtypes", [])
    ], EnumerationTypeDetailViewModelBase.prototype, "enumerationTypeColorService", null);
    __decorate([
        computedFrom('_enumerationTypesEnum'),
        __metadata("design:type", Object),
        __metadata("design:paramtypes", [])
    ], EnumerationTypeDetailViewModelBase.prototype, "enumerationTypesEnum", null);
    __decorate([
        computedFrom('_category'),
        __metadata("design:type", Number),
        __metadata("design:paramtypes", [])
    ], EnumerationTypeDetailViewModelBase.prototype, "category", null);
    __decorate([
        computedFrom('_category'),
        __metadata("design:type", Object),
        __metadata("design:paramtypes", [])
    ], EnumerationTypeDetailViewModelBase.prototype, "enumerationTypeConfig", null);
    __decorate([
        computedFrom('category'),
        __metadata("design:type", Object),
        __metadata("design:paramtypes", [])
    ], EnumerationTypeDetailViewModelBase.prototype, "ribbonHeaderText", null);
    __decorate([
        computedFrom('category', 'editingMode', 'entity.denomination._translation'),
        __metadata("design:type", Object),
        __metadata("design:paramtypes", [])
    ], EnumerationTypeDetailViewModelBase.prototype, "documentTitle", null);
    __decorate([
        computedFrom('config.enumerationTypeConfig.isUniqueCodeRequired'),
        __metadata("design:type", Boolean),
        __metadata("design:paramtypes", [])
    ], EnumerationTypeDetailViewModelBase.prototype, "isUniqueCodeRequired", null);
    EnumerationTypeDetailViewModelBase = __decorate([
        autoinject,
        __metadata("design:paramtypes", [Router, CustomLogger, I18N, BindingEngine, Boolean])
    ], EnumerationTypeDetailViewModelBase);
    return EnumerationTypeDetailViewModelBase;
}(EntityDetailViewModelBase));

//# sourceMappingURL=enumeration-type-detail-view-model-base.js.map
