"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
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 __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BreezeModel = void 0;
var translated_property_helper_1 = require("./../utils/translated-property-helper");
var aurelia_framework_1 = require("aurelia-framework");
var aurelia_i18n_1 = require("aurelia-i18n");
var breeze = __importStar(require("breeze-client"));
var moment_1 = __importDefault(require("moment"));
var custom_logger_1 = require("../modules/custom-logger");
var data_context_1 = require("./data-context");
var aurelia_validation_1 = require("aurelia-validation");
var BreezeModel = exports.BreezeModel = (function () {
    function BreezeModel(i18N, logger, datacontext, translatedPropertyHelper) {
        this.i18N = i18N;
        this.logger = logger;
        this.datacontext = datacontext;
        this.translatedPropertyHelper = translatedPropertyHelper;
    }
    BreezeModel.prototype.addValidationRules = function (entityType) {
        var _this = this;
        if (entityType) {
            entityType.dataProperties.forEach(function (dp) {
                var castDp = dp;
                if (castDp.custom != null && castDp.custom.length > 0) {
                    castDp.custom.forEach(function (validator) {
                        if (validator.Name == "RegularExpressionAttribute") {
                            var regexValidator = breeze.Validator.makeRegExpValidator("regularExpressionValidator-".concat(entityType.name, "-").concat(dp.name, "\""), validator.ValidatorParam, _this.i18N.tr("validation.regex", { ns: "common" }));
                            breeze.Validator.register(regexValidator);
                            dp.validators.push(regexValidator);
                        }
                        else if (validator.Name == "DateGreaterThanAttribute") {
                            if (validator.ValidatorParam.length > 0) {
                                var startDateName_1 = validator.ValidatorParam.charAt(0).toLowerCase() + validator.ValidatorParam.slice(1);
                                var parentName = dp.parentType.shortName.toLocaleLowerCase();
                                var dateGreaterThanValidator = new breeze.Validator("dateGreaterThanValidator-".concat(entityType.name, "-").concat(dp.name, "\""), function (value, context) {
                                    var startDate = context.entity.getProperty(startDateName_1);
                                    var endDate = value;
                                    if (endDate != null) {
                                        return startDate < endDate;
                                    }
                                    return true;
                                }, {
                                    messageTemplate: _this.i18N.tr("validation.mustBeGreaterThan", { ns: "common", otherPropertyName: _this.i18N.tr(parentName + "." + startDateName_1) })
                                });
                                breeze.Validator.register(dateGreaterThanValidator);
                                dp.validators.push(dateGreaterThanValidator);
                            }
                        }
                        else if (validator.Name == "EmailAddressAttribute") {
                            dp.validators.push(breeze.Validator.emailAddress());
                        }
                    });
                }
            });
            this.logger.Log('Validation rules added', entityType.name, null, false);
        }
    };
    BreezeModel.prototype.createNullo = function (entityName, manager, values) {
        var initialValues = values
            || { name: ' [Select a ' + entityName.toLowerCase() + ']' };
        return manager.createEntity(entityName, initialValues, breeze.EntityState.Unchanged);
    };
    BreezeModel.prototype.forceMetaDataCustomProperties = function (entityType) {
        var _this = this;
        entityType.dataProperties.forEach(function (dp) {
            var customIsUnmapped = _this.getCustomMetadataPropertyValue(dp, "isUnmapped");
            var customIsSettable = _this.getCustomMetadataPropertyValue(dp, "isSettable");
            var customIsDatabaseGenerated = _this.getCustomMetadataPropertyValue(dp, "isDatabaseGenerated");
            if (customIsSettable == false && customIsDatabaseGenerated == true) {
                dp.isUnmapped = false;
            }
            else if (customIsSettable == false) {
                dp.isUnmapped = true;
            }
            else if (customIsUnmapped != null && customIsUnmapped != dp.isUnmapped) {
                dp.isUnmapped = customIsUnmapped;
            }
            if (dp.isUnmapped && !entityType.unmappedProperties.some(function (p) { return dp.name == p.name; }))
                entityType.unmappedProperties.push(dp);
        });
    };
    BreezeModel.prototype.getCustomMetadataPropertyValue = function (dp, name) {
        var _a;
        if (Array.isArray(dp === null || dp === void 0 ? void 0 : dp.custom)) {
            return (_a = dp.custom.find(function (x) { return x[name] != null; })) === null || _a === void 0 ? void 0 : _a[name];
        }
        return null;
    };
    BreezeModel.prototype.configureMetadataStore = function (metadataStore, manager) {
        var _this = this;
        function qualifyURL(url) {
            var a = document.createElement('a');
            a.href = url;
            return a.cloneNode(false).href;
        }
        ;
        this.configureInitializerAndCtor(metadataStore, manager);
        var allEntityTypes = metadataStore.getEntityTypes();
        allEntityTypes.forEach(function (entityType) {
            _this.forceMetaDataCustomProperties(entityType);
            _this.addValidationRules(entityType);
            var ctorRegistry = metadataStore._ctorRegistry;
            var initializerFn = function (entity) {
                if (entity.isSelected == null)
                    entity.isSelected = false;
                _this.detectTranslatedProperties(entityType, entity);
                _this.initializeCommonEntities(entityType, entity);
            };
            if (ctorRegistry[entityType.name] == null) {
                metadataStore.registerEntityTypeCtor(entityType.name, null, initializerFn);
            }
            else {
                var existingInitializerFn = ctorRegistry[entityType.name].initFn;
                var newInitFn = function (entity) {
                    initializerFn(entity);
                    if (existingInitializerFn != null)
                        existingInitializerFn(entity);
                };
                ctorRegistry[entityType.name].initFn = newInitFn;
                entityType.getCtor(true);
            }
        });
        this.addCustomValidationRules();
    };
    BreezeModel.prototype.addCustomValidationRules = function () {
        aurelia_validation_1.ValidationRules.customRule('validate-date', function (val, obj, format) {
            var isNullOrEmpty = function (arg) {
                if (arg == null || arg === "")
                    return true;
                return false;
            };
            var aDate = (0, moment_1.default)(val, format, true);
            var invalidDate = !isNullOrEmpty(val) && !aDate.isValid();
            return !invalidDate;
        }, this.i18N.tr("validation.invalidDate", { ns: "common" }));
    };
    BreezeModel.prototype.initializeCommonEntities = function (entityType, entity) {
        if (entityType.shortName == 'Language') {
            Object.defineProperty(entity, '_columnName', {
                get: function () {
                    return "lang" + entity.columnIndex;
                }
            });
            Object.defineProperty(entity, '_flag', {
                get: function () {
                    var entityAny = entity;
                    if (entityAny.code == 'en')
                        return 'gb';
                    else
                        return entityAny.code;
                }
            });
        }
    };
    BreezeModel.prototype.detectTranslatedProperties = function (entityType, entity) {
        var _this = this;
        var translatedProperties = entityType.complexProperties.filter(function (cp) { return cp.dataType.shortName == 'TranslatedProperty'; });
        if (translatedProperties != null && translatedProperties.length > 0) {
            translatedProperties.forEach(function (prop) {
                var _a;
                if ((_a = entity[prop.name]) === null || _a === void 0 ? void 0 : _a.hasOwnProperty('_translation')) {
                    return;
                }
                _this.translatedPropertyHelper.addNecessaryProperties(entity[prop.name], true);
            });
        }
    };
    BreezeModel = __decorate([
        (0, aurelia_framework_1.inject)(aurelia_i18n_1.I18N, custom_logger_1.CustomLogger, data_context_1.Datacontext, translated_property_helper_1.TranslatedPropertyHelper),
        __metadata("design:paramtypes", [aurelia_i18n_1.I18N, custom_logger_1.CustomLogger, data_context_1.Datacontext, translated_property_helper_1.TranslatedPropertyHelper])
    ], BreezeModel);
    return BreezeModel;
}());

//# sourceMappingURL=breeze-model.js.map
