"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 __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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AgGridToBreezeTransformer = exports.ServiceBase = void 0;
var ui_entity_history_1 = require("./../ui/history/ui-entity-history");
var aurelia_framework_1 = require("aurelia-framework");
var box_1 = require("../modules/box");
var config_1 = require("../config");
var data_source_1 = require("./data-source");
var aurelia_i18n_1 = require("aurelia-i18n");
var repository_1 = require("./repository");
var entity_manager_1 = require("./entity-manager");
var custom_logger_1 = require("../modules/custom-logger");
var breeze = __importStar(require("breeze-client"));
var moment_1 = __importDefault(require("moment"));
var ui_internal_1 = require("../utils/ui-internal");
var constants_1 = require("./../constants/constants");
var ServiceBase = (function () {
    function ServiceBase(entityTypeName, customContextOptions, resourceName) {
        if (customContextOptions === void 0) { customContextOptions = null; }
        var _this = this;
        this.entityTypeName = entityTypeName;
        this.resourceName = resourceName;
        this.i18n = aurelia_framework_1.Container.instance.get(aurelia_i18n_1.I18N);
        var entityManager;
        if (customContextOptions == null || customContextOptions.uri == null || customContextOptions.uri.length == 0) {
            entityManager = aurelia_framework_1.Container.instance.get(entity_manager_1.EntityManager);
        }
        else {
            entityManager = new entity_manager_1.EntityManager(this.i18n, null);
            entityManager.initialize(customContextOptions.uri, customContextOptions.metadata);
        }
        this.box = aurelia_framework_1.Container.instance.get(box_1.Box);
        this.manager = entityManager.manager;
        this.logger = aurelia_framework_1.Container.instance.get(custom_logger_1.CustomLogger);
        this.config = aurelia_framework_1.Container.instance.get(config_1.Config);
        if (this.resourceName == null || this.resourceName.length == 0) {
            this.resourceName = this.config.globalConfig.resourceNames[this.entityTypeName];
        }
        this.repository = new repository_1.Repository(this.manager, this.logger, this.entityTypeName, this.resourceName, this.i18n);
        this.getDisplayNames(this.entityTypeName);
        this.gridDataSource = new data_source_1.GridDataSource(this.entityTypeName, entityManager.manager.metadataStore);
        this.gridDataSource.getDataFunction = function (params, expands, quickFilter, queryCriteria, queryParameters) {
            if (expands === void 0) { expands = null; }
            if (quickFilter === void 0) { quickFilter = null; }
            if (queryCriteria === void 0) { queryCriteria = null; }
            if (queryParameters === void 0) { queryParameters = null; }
            return _this.fetchForDataGrid(_this.resourceName, params, expands, quickFilter, _this.gridDataSource, queryParameters);
        };
        this.gridDataSource.getPredicatesFunction = function (filterText) { return _this.getDefaultPredicates(filterText); };
    }
    ServiceBase.prototype.createEntity = function (initialValues, sync) {
        if (initialValues === void 0) { initialValues = null; }
        if (sync === void 0) { sync = false; }
        var fn = 'createEntity' + (sync ? 'Sync' : '');
        return this.repository[fn](initialValues);
    };
    ServiceBase.prototype.createLinkedEntity = function (linkedEntityName, initialValues, avoidMultipleAdd) {
        if (initialValues === void 0) { initialValues = null; }
        if (avoidMultipleAdd === void 0) { avoidMultipleAdd = false; }
        var linkedRepository = new repository_1.Repository(this.manager, this.logger, linkedEntityName, this.config.globalConfig.resourceNames[linkedEntityName], this.i18n);
        var existingEntity = linkedRepository.restoreDeletedEntity(initialValues);
        if (avoidMultipleAdd) {
            existingEntity = linkedRepository.findAddedEntity(initialValues);
        }
        if (existingEntity != null) {
            return Promise.resolve(existingEntity);
        }
        else {
            return linkedRepository.createEntity(initialValues);
        }
    };
    ServiceBase.prototype.deleteEntities = function (entitiesToDelete, detachInverseFKEntities, beforeSaveAction, force) {
        var _this = this;
        if (beforeSaveAction === void 0) { beforeSaveAction = null; }
        if (force === void 0) { force = false; }
        var promise = new Promise(function (resolve, reject) {
            var msg = _this.i18n.tr('menu.delete_confirmation', { count: entitiesToDelete.length });
            if (entitiesToDelete.length === 0) {
                _this.box.showWarning(_this.i18n.tr('general.noRecordsSelected', { ns: "common" }), _this.i18n.tr("general.warning", { ns: "common" }));
                resolve(false);
            }
            else {
                var internalDeleteEntities_1 = function () {
                    return _this.repository.deleteEntities(entitiesToDelete, detachInverseFKEntities, beforeSaveAction)
                        .then(function () {
                        _this.logger.Log(msg, null, null, null);
                        _this.unselectAll(entitiesToDelete);
                        resolve(true);
                        ui_internal_1.UIInternal.broadcast(ui_entity_history_1.EVT_REFRESH_HISTORY);
                    })
                        .catch(function (errors) {
                        if (errors.entityErrors) {
                            _this.unselectAll(entitiesToDelete);
                            _this.repository.cancelChanges(true);
                        }
                        reject();
                    });
                };
                if (force) {
                    return internalDeleteEntities_1();
                }
                else {
                    var buttonOk = {
                        label: _this.i18n.tr("general.remove", { ns: "common" }),
                        title: _this.i18n.tr("general.remove", { ns: "common" }),
                        theme: 'primary',
                        type: 'solid',
                        disabled: false,
                        fn: function (thisBox) { thisBox.controller.ok(); },
                        keyboardShortcut: _this.config.globalConfig.keyboardShortcutFwBox ? constants_1.KeyboardShortcut.Enter : null
                    };
                    var buttonCancel = {
                        label: _this.i18n.tr("general.cancel", { ns: "common" }),
                        title: _this.i18n.tr("general.cancel", { ns: "common" }),
                        theme: 'dark',
                        type: 'ghost',
                        disabled: false,
                        fn: function (thisBox) { thisBox.controller.cancel(); },
                        keyboardShortcut: _this.config.globalConfig.keyboardShortcutFwBox ? [constants_1.KeyboardShortcut.Escape, constants_1.KeyboardShortcut.Backspace] : null
                    };
                    _this.box.showQuestion(msg, _this.i18n.tr("menu.question", { ns: "common" }), [buttonCancel, buttonOk]).then(function (selectedOption) {
                        selectedOption.closeResult.then(function (result) {
                            if (result.wasCancelled) {
                                resolve(false);
                            }
                            else {
                                internalDeleteEntities_1();
                            }
                        });
                    });
                }
            }
        });
        return promise;
    };
    ServiceBase.prototype.fetchForDataGrid = function (resourceNames, params, expands, quickFilter, queryCriteria, queryParameters) {
        if (expands === void 0) { expands = null; }
        if (quickFilter === void 0) { quickFilter = null; }
        if (queryParameters === void 0) { queryParameters = null; }
        return this.repository.fetchForDataGrid(resourceNames, params, expands, quickFilter, queryCriteria, queryParameters);
    };
    ServiceBase.prototype.getEntityById = function (id) {
        var expands = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            expands[_i - 1] = arguments[_i];
        }
        return this.repository.getEntityById(id, expands);
    };
    ServiceBase.prototype.getEntityByIdFromLocalCache = function (id) {
        var expands = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            expands[_i - 1] = arguments[_i];
        }
        return this.repository.getEntityById(id, expands, true);
    };
    ServiceBase.prototype.getAllEntities = function () {
        var expands = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            expands[_i] = arguments[_i];
        }
        return this.repository.getAllEntities(expands);
    };
    ServiceBase.prototype.getEntities = function (predicates, expands, parameters, orderBy, paging) {
        if (predicates === void 0) { predicates = null; }
        if (expands === void 0) { expands = null; }
        if (parameters === void 0) { parameters = null; }
        return this.repository.getEntities(predicates, expands, parameters, orderBy, paging);
    };
    ServiceBase.prototype.getEntitiesFromDataSource = function (predicates, expands, parameters, orderBy, paging) {
        if (predicates === void 0) { predicates = null; }
        if (expands === void 0) { expands = null; }
        if (parameters === void 0) { parameters = null; }
        return this.repository.getEntities(predicates !== null && predicates !== void 0 ? predicates : this.gridDataSource.predicates, expands !== null && expands !== void 0 ? expands : this.gridDataSource.expands, parameters !== null && parameters !== void 0 ? parameters : this.gridDataSource.queryParameters, orderBy !== null && orderBy !== void 0 ? orderBy : this.gridDataSource.queryOrderBy, paging !== null && paging !== void 0 ? paging : this.gridDataSource.queryPaging);
    };
    ServiceBase.prototype.getEntitiesFromLocalCache = function (predicates, expands, orderBy, paging) {
        if (predicates === void 0) { predicates = null; }
        if (expands === void 0) { expands = null; }
        return this.repository.getEntitiesFromLocalCache(predicates, expands, orderBy, paging);
    };
    ServiceBase.prototype.getCount = function (predicates, parameters) {
        if (predicates === void 0) { predicates = null; }
        if (parameters === void 0) { parameters = null; }
        return this.repository.getCount(predicates, parameters);
    };
    ServiceBase.prototype.firstEntity = function (predicates, expands, parameters, orderBy, skip) {
        if (predicates === void 0) { predicates = null; }
        if (expands === void 0) { expands = null; }
        if (parameters === void 0) { parameters = null; }
        return this.repository.firstEntity(predicates, expands, parameters, orderBy, skip);
    };
    ServiceBase.prototype.save = function (silentSave, byPassLocking) {
        if (silentSave === void 0) { silentSave = true; }
        return this.repository.saveChanges(null, silentSave, byPassLocking).then(function () {
            ui_internal_1.UIInternal.broadcast(ui_entity_history_1.EVT_REFRESH_HISTORY);
        });
    };
    ServiceBase.prototype.saveEntity = function (entityToSave, silentSave) {
        if (silentSave === void 0) { silentSave = false; }
        return this.repository.saveChanges([entityToSave], silentSave).then(function () {
            ui_internal_1.UIInternal.broadcast(ui_entity_history_1.EVT_REFRESH_HISTORY);
        });
    };
    ServiceBase.prototype.saveEntities = function (entitiesToSave, silentSave) {
        if (silentSave === void 0) { silentSave = false; }
        return this.repository.saveChanges(entitiesToSave, silentSave).then(function () {
            ui_internal_1.UIInternal.broadcast(ui_entity_history_1.EVT_REFRESH_HISTORY);
        });
    };
    ServiceBase.prototype.lockRecordForEditing = function (entity) {
        return this.repository.lockRecordForEditing(entity);
    };
    ServiceBase.prototype.cancel = function (silentMode) {
        if (silentMode === void 0) { silentMode = true; }
        return this.repository.cancelChanges(silentMode);
    };
    ServiceBase.prototype.getDefaultPredicates = function (filterText) {
        var entityType = this.manager.metadataStore.getEntityType(this.entityTypeName);
        var predicates = null;
        if (filterText != null && filterText.length > 0) {
            entityType.dataProperties.forEach(function (prop) {
                if (prop.dataType === breeze.DataType.String && prop.enumType == null) {
                    if (predicates == null) {
                        predicates = new breeze.Predicate(prop.name, breeze.FilterQueryOp.Contains, filterText);
                    }
                    else {
                        predicates = predicates.or(new breeze.Predicate(prop.name, breeze.FilterQueryOp.Contains, filterText));
                    }
                }
            }, this);
        }
        return predicates;
    };
    ServiceBase.prototype.rejectAnyEntityChangesFromCache = function (entityTypeName) {
        var addedEntities = this.manager.getEntities(entityTypeName, breeze.EntityState.Added);
        var modifiedEntities = this.manager.getEntities(entityTypeName, breeze.EntityState.Modified);
        var deletedEntities = this.manager.getEntities(entityTypeName, breeze.EntityState.Deleted);
        addedEntities.concat(modifiedEntities).concat(deletedEntities).forEach(function (elm) { elm.entityAspect.rejectChanges(); });
    };
    ServiceBase.prototype.unselectAll = function (selectedEntities) {
        selectedEntities = [];
    };
    ServiceBase.prototype.getDisplayNames = function (entityTypeName) {
        var _this = this;
        var _a;
        var metadata = this.manager.metadataStore.getEntityType(entityTypeName, true);
        if (metadata != null) {
            if (this.displayNames == null) {
                this.displayNames = new Array();
            }
            if ((_a = metadata.getProperties()) === null || _a === void 0 ? void 0 : _a.some(function (x) { return _this.hasCustomDisplayNameAttribute(x); })) {
                var property = metadata.getProperties().find(function (x) { return _this.hasCustomDisplayNameAttribute(x); });
                this.displayNames.push(property.name);
                if (property.isNavigationProperty) {
                    this.getDisplayNames(property.entityType.shortName);
                }
            }
        }
    };
    ServiceBase.prototype.hasCustomDisplayNameAttribute = function (property) {
        var _a;
        return (_a = property === null || property === void 0 ? void 0 : property.custom) === null || _a === void 0 ? void 0 : _a.some(function (y) { return (y === null || y === void 0 ? void 0 : y.Name) == "DisplayNameAttribute"; });
    };
    ServiceBase.prototype.getDisplayNameValue = function (entity) {
        var displayNameValue = null;
        if (this.displayNames != null && entity != null) {
            try {
                var entityDisplay_1 = entity;
                this.displayNames.forEach(function (displayName) {
                    entityDisplay_1 = entityDisplay_1[displayName];
                });
                displayNameValue = entityDisplay_1;
            }
            catch (_a) { }
        }
        if (displayNameValue === null || displayNameValue === void 0 ? void 0 : displayNameValue.hasOwnProperty('_translation')) {
            displayNameValue = displayNameValue._translation;
        }
        return displayNameValue;
    };
    ServiceBase.prototype.setAllDetached = function (entities) {
        var length = entities.length;
        while (length > 0) {
            var entity = entities[length - 1];
            if (entity.entityAspect.entityState.isAdded()) {
                entity.entityAspect.setDetached();
            }
            length--;
        }
    };
    return ServiceBase;
}());
exports.ServiceBase = ServiceBase;
var AgGridToBreezeTransformer = (function () {
    function AgGridToBreezeTransformer(resourceName) {
        this.resourceName = resourceName;
        this.manager = aurelia_framework_1.Container.instance.get(entity_manager_1.EntityManager).manager;
    }
    AgGridToBreezeTransformer.prototype.getRequestObject = function (ds, request) {
        var predicates = this.getPredicatesFromParams(request.filterModel, ds.filterText);
        var sortClause = this.getSortClause(request.sortModel);
        return {
            predicates: predicates,
            sortClause: sortClause,
            expands: ds.expands,
            queryParameters: ds.queryParameters,
            start: request.startRow,
            end: request.endRow
        };
    };
    AgGridToBreezeTransformer.prototype.getPredicatesFromParams = function (filterModel, filterText) {
        var _this = this;
        var predicates = null;
        var filterPresent = filterModel && Object.keys(filterModel).length > 0;
        if (filterPresent) {
            Object.keys(filterModel).forEach(function (f) {
                var filter = filterModel[f];
                var pred1, pred2, predX = null;
                if (filter.hasOwnProperty("condition1") &&
                    filter.hasOwnProperty("condition2") &&
                    filter.hasOwnProperty("operator")) {
                    pred1 = _this.extractPredicatesFromFilter(filter["condition1"], f);
                    pred2 = _this.extractPredicatesFromFilter(filter["condition2"], f);
                    predX = (filter["operator"] == "AND") ? pred1.and(pred2) : pred1.or(pred2);
                }
                else {
                    predX = _this.extractPredicatesFromFilter(filter, f);
                }
                predicates = (predicates == null) ? predX : predicates.and(predX);
            });
        }
        predicates = this.fillPredicatesWithQuickFilter(predicates, filterText);
        return predicates;
    };
    AgGridToBreezeTransformer.prototype.getSortClause = function (sortModel) {
        if (sortModel && sortModel.length > 0) {
            var sortArray = sortModel;
            var orderByClause_1 = "";
            sortArray.forEach(function (c) {
                if (orderByClause_1.length > 0)
                    orderByClause_1 += ", ";
                orderByClause_1 += c.colId;
                orderByClause_1 += " " + c.sort;
            });
            return orderByClause_1;
        }
        else {
            var entityTypeName = this.manager.metadataStore.getEntityTypeNameForResourceName(this.resourceName);
            var entityType = this.manager.metadataStore.getEntityType(entityTypeName);
            var idDp = entityType.dataProperties.filter(function (dp) { return dp.isPartOfKey == true && dp.name == 'id'; });
            if (idDp != null && idDp.length > 0) {
                return "id asc";
            }
            return null;
        }
        return null;
    };
    AgGridToBreezeTransformer.prototype.extractPredicatesFromFilter = function (filter, f) {
        var predicates = null;
        if (filter) {
            if (filter.filterType == 'date') {
                var operator = this.getBreezeOperatorFromFilterType(filter.type);
                if (operator != null) {
                    if (operator === breeze.FilterQueryOp.Equals) {
                        var dateFrom = (0, moment_1.default)(filter.dateFrom).toDate();
                        var dateTo = filter.type === 'inRange' ? (0, moment_1.default)(filter.dateTo).add(moment_1.default.duration(24 * 3600 * 1000)).toDate() : (0, moment_1.default)(filter.dateFrom).add(moment_1.default.duration(24 * 3600 * 1000)).toDate();
                        if (predicates == null)
                            predicates = new breeze.Predicate(f, breeze.FilterQueryOp.GreaterThanOrEqual, dateFrom).and(new breeze.Predicate(f, breeze.FilterQueryOp.LessThanOrEqual, dateTo));
                        else
                            predicates = predicates.and(new breeze.Predicate(f, breeze.FilterQueryOp.GreaterThanOrEqual, dateFrom).and(new breeze.Predicate(f, breeze.FilterQueryOp.LessThanOrEqual, dateTo)));
                    }
                    else if (operator === breeze.FilterQueryOp.NotEquals) {
                        var dateFrom = (0, moment_1.default)(filter.dateFrom).toDate();
                        var dateTo = (0, moment_1.default)(filter.dateFrom).add(moment_1.default.duration(24 * 3600 * 1000)).toDate();
                        if (predicates == null)
                            predicates = new breeze.Predicate(f, breeze.FilterQueryOp.LessThan, dateFrom).or(new breeze.Predicate(f, breeze.FilterQueryOp.GreaterThanOrEqual, dateTo));
                        else
                            predicates = predicates.and(new breeze.Predicate(f, breeze.FilterQueryOp.LessThan, dateFrom).or(new breeze.Predicate(f, breeze.FilterQueryOp.GreaterThanOrEqual, dateTo)));
                    }
                    else {
                        if (predicates == null)
                            predicates = new breeze.Predicate(f, operator, filter.dateFrom);
                        else
                            predicates = predicates.and(new breeze.Predicate(f, operator, filter.dateFrom));
                    }
                }
            }
            else if (filter.filterType == 'set') {
                var pred = null;
                filter.values.forEach(function (v) {
                    if (pred == null)
                        pred = new breeze.Predicate(f, breeze.FilterQueryOp.Equals, v);
                    else
                        pred = pred.or(new breeze.Predicate(f, breeze.FilterQueryOp.Equals, v));
                });
                if (predicates == null)
                    predicates = pred;
                else
                    predicates = predicates.and(pred);
            }
            else if (filter.type != null && filter.filterType == 'text') {
                var operator = this.getBreezeOperatorFromFilterType(filter.type);
                if (predicates == null)
                    predicates = new breeze.Predicate(f, operator, filter.filter);
                else
                    predicates = predicates.and(new breeze.Predicate(f, operator, filter.filter));
            }
            else if (filter.type == null && filter.length > 0) {
                var filterArray = filter;
                var newPredicates = null;
                filterArray.forEach(function (value) {
                    if (newPredicates == null) {
                        newPredicates = new breeze.Predicate(f, breeze.FilterQueryOp.Equals, value);
                    }
                    else {
                        newPredicates = newPredicates.or(new breeze.Predicate(f, breeze.FilterQueryOp.Equals, value));
                    }
                });
                if (predicates == null)
                    predicates = newPredicates;
                else
                    predicates = predicates.and(newPredicates);
            }
        }
        return predicates;
    };
    AgGridToBreezeTransformer.prototype.getBreezeOperatorFromFilterType = function (filterType) {
        switch (filterType) {
            case 'contains':
                return breeze.FilterQueryOp.Contains;
            case 'notEqual':
                return breeze.FilterQueryOp.NotEquals;
            case 'inRange':
            case 'equals':
                return breeze.FilterQueryOp.Equals;
            case 'startsWith':
                return breeze.FilterQueryOp.StartsWith;
            case 'endsWith':
                return breeze.FilterQueryOp.EndsWith;
            case 'greaterThan':
                return breeze.FilterQueryOp.GreaterThanOrEqual;
            case 'lessThan':
                return breeze.FilterQueryOp.LessThanOrEqual;
            default:
                return null;
        }
    };
    AgGridToBreezeTransformer.prototype.fillPredicatesWithQuickFilter = function (predicates, filterText) {
        if (filterText != null && filterText.length > 0) {
            var entityTypeName = this.manager.metadataStore.getEntityTypeNameForResourceName(this.resourceName);
            var entityType = this.manager.metadataStore.getEntityType(entityTypeName);
            var newPredicates = null;
            var index = 0;
            entityType.dataProperties.forEach(function (dp) {
                if (dp.dataType == breeze.DataType.String && dp.enumType == null) {
                    if (index == 0) {
                        newPredicates = new breeze.Predicate(dp.name, breeze.FilterQueryOp.Contains, filterText);
                    }
                    else {
                        newPredicates = newPredicates.or(new breeze.Predicate(dp.name, breeze.FilterQueryOp.Contains, filterText));
                    }
                    index++;
                }
            });
            if (predicates == null) {
                predicates = newPredicates;
            }
            else {
                predicates = predicates.and(newPredicates);
            }
        }
        return predicates;
    };
    return AgGridToBreezeTransformer;
}());
exports.AgGridToBreezeTransformer = AgGridToBreezeTransformer;

//# sourceMappingURL=service-base.js.map
