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 { ViewModelBase } from './view-model-base';
import { EntityManager } from '../data/entity-manager';
import * as breeze from 'breeze-client';
import { Container, observable, computedFrom, inject } from 'aurelia-framework';
import { Router } from 'aurelia-router';
import { CustomLogger } from '../modules/custom-logger';
import { EditingModeEnum } from './editing-mode-enum';
import { DialogService } from 'aurelia-dialog';
import { ValidationController, Validator, GlobalValidationConfiguration, PropertyAccessorParser } from 'aurelia-validation';
import { Config } from '../config';
import { KeyboardShortcut } from './../constants/constants';
export var EntityDetailViewModelBase = (function (_super) {
    __extends(EntityDetailViewModelBase, _super);
    function EntityDetailViewModelBase(router, logger) {
        var _this = _super.call(this, router, logger) || this;
        _this.hasChanges = false;
        _this.isInitialized = false;
        _this.isSaving = false;
        _this.dialogRightActions = [];
        _this.dialogLeftActions = [];
        _this.entityManager = Container.instance.get(EntityManager);
        _this.hasChanges = _this.entityManager.manager.hasChanges();
        _this.controller = new ValidationController(Container.instance.get(Validator), Container.instance.get(PropertyAccessorParser), Container.instance.get(GlobalValidationConfiguration));
        _this.dialogService = Container.instance.get(DialogService);
        _this.hasChangesSubscriptionKey = _this.entityManager.manager.hasChangesChanged.subscribe(function (data) {
            _this.hasChanges = data.hasChanges;
        });
        _this.handleShortcutsEvent = function (event) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4, this.handleShortcuts.call(this, event)];
                case 1: return [2, _a.sent()];
            }
        }); }); };
        document.addEventListener("keydown", _this.handleShortcutsEvent, false);
        return _this;
    }
    Object.defineProperty(EntityDetailViewModelBase.prototype, "isEditable", {
        get: function () {
            if (this.entity == null)
                return false;
            if (this.editingMode === EditingModeEnum.Create)
                return true;
            return this.entity.isEditable;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EntityDetailViewModelBase.prototype, "canEdit", {
        get: function () {
            if (this.entity == null)
                return false;
            if (this.editingMode == EditingModeEnum.Create) {
                return false;
            }
            return this.entity.isLockable && this.canUpdate;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EntityDetailViewModelBase.prototype, "disabled", {
        get: function () {
            return !this.isEditable;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EntityDetailViewModelBase.prototype, "canSave", {
        get: function () {
            return this.hasChanges && !this.isSaving;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EntityDetailViewModelBase.prototype, "isCreationMode", {
        get: function () {
            return this.editingMode == EditingModeEnum.Create;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(EntityDetailViewModelBase.prototype, "canAddOrUpdate", {
        get: function () {
            if (this.isCreationMode) {
                return this.canAdd;
            }
            return this.canUpdate;
        },
        enumerable: false,
        configurable: true
    });
    EntityDetailViewModelBase.prototype.isSavingChanged = function (newValue, oldValue) {
        this.showLoadingSpinner = (newValue === true);
    };
    EntityDetailViewModelBase.prototype.initialize = function (serviceInstance) {
        if (serviceInstance != null) {
            this.isInitialized = true;
        }
        this.service = serviceInstance;
    };
    EntityDetailViewModelBase.prototype.getTranslationKeyEntityTypeName = function () {
        var loweredEntityTypeName = this.service.entityTypeName.toLocaleLowerCase();
        return loweredEntityTypeName + "." + loweredEntityTypeName;
    };
    Object.defineProperty(EntityDetailViewModelBase.prototype, "ribbonHeaderText", {
        get: function () {
            var _a;
            var docTitle = this.documentTitle;
            if (this.editingMode === EditingModeEnum.Update) {
                var translatedEntityTypeName = this.i18n.tr(this.getTranslationKeyEntityTypeName());
                if (docTitle == null && this.service != null) {
                    docTitle = (_a = this.service.getDisplayNameValue(this.entity)) !== null && _a !== void 0 ? _a : '';
                }
                if (this.isEditable)
                    return translatedEntityTypeName + " : " + docTitle + " (" + this.i18n.tr("menu.editInProgress") + ")";
                return translatedEntityTypeName + " : " + docTitle;
            }
            return docTitle;
        },
        enumerable: false,
        configurable: true
    });
    EntityDetailViewModelBase.prototype.cancel = function (silentCancel, onlyCurrentEntity) {
        if (silentCancel === void 0) { silentCancel = false; }
        if (onlyCurrentEntity === void 0) { onlyCurrentEntity = false; }
        return this.innerCancel(true, silentCancel, onlyCurrentEntity);
    };
    EntityDetailViewModelBase.prototype.innerCancel = function (allowNavigateBack, silentMode, onlyCurrentEntity) {
        var _this = this;
        if (allowNavigateBack === void 0) { allowNavigateBack = true; }
        if (silentMode === void 0) { silentMode = false; }
        if (onlyCurrentEntity === void 0) { onlyCurrentEntity = false; }
        if (this.isSaving)
            return Promise.reject(false);
        var p = new Promise(function (resolve, reject) {
            if (_this.hasChanges === true) {
                if (onlyCurrentEntity == true) {
                    _this.entity.entityAspect.rejectChanges();
                    resolve(true);
                }
                else {
                    _this.service.cancel(silentMode);
                    resolve(true);
                }
            }
            _this.controller.removeObject(_this.entity);
            if (allowNavigateBack && _this.editingMode === EditingModeEnum.Create) {
                _this.doNavigateBack();
            }
            resolve(true);
        });
        return p;
    };
    EntityDetailViewModelBase.prototype.edit = function () {
        var _this = this;
        this.isSaving = true;
        return this.service.lockRecordForEditing(this.entity)
            .catch(function (errors) {
            console.log('Rejection of the Promise');
            _this.isSaving = false;
            return Promise.reject(errors);
        })
            .then(function () { return _this.isSaving = false; });
    };
    EntityDetailViewModelBase.prototype.refreshData = function () { };
    EntityDetailViewModelBase.prototype.deactivate = function () {
        this.entityManager.manager.hasChangesChanged.unsubscribe(this.hasChangesSubscriptionKey);
        document.removeEventListener("keydown", this.handleShortcutsEvent, false);
    };
    EntityDetailViewModelBase.prototype.canDeactivate = function () {
        var _this = this;
        var msg = this.i18n.tr("general.doYouWantToSave", { ns: "common" });
        var buttonSave = {
            label: this.i18n.tr("general.save", { ns: "common" }),
            title: this.i18n.tr("general.save", { ns: "common" }),
            theme: 'primary',
            type: 'solid',
            disabled: false,
            fn: function (thisBox) { thisBox.controller.ok(true); },
            keyboardShortcut: this.config.globalConfig.keyboardShortcutFwBox ? KeyboardShortcut.Enter : null
        };
        var buttonIgnore = {
            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.ok(false); },
            keyboardShortcut: this.config.globalConfig.keyboardShortcutFwBox ? [KeyboardShortcut.Escape, KeyboardShortcut.Backspace] : null
        };
        var p = new Promise(function (resolve, reject) {
            if (_this.isSaving === true) {
                _this.logError("Save in progress", "");
                return resolve(false);
            }
            if (!_this.hasChanges === true && _this.isEditable && _this.editingMode !== EditingModeEnum.Create) {
                return _this.cancel()
                    .then(function () { return resolve(true); })
                    .catch(function () { return resolve(false); });
            }
            if (_this.hasChanges === true) {
                var asksToSave = function () {
                    var confirm = function (dor) {
                        dor.closeResult.then(function (result) {
                            if (!result.wasCancelled) {
                                if (result.output === true) {
                                    _this.innerSave(false)
                                        .then(function () {
                                        resolve(true);
                                    })
                                        .catch(function () {
                                        resolve(false);
                                    });
                                }
                                else if (result.output === false) {
                                    _this.innerCancel(false);
                                    resolve(true);
                                }
                            }
                            else {
                                resolve(false);
                            }
                        });
                    };
                    _this.box.showQuestion(msg, _this.config.globalConfig.applicationTitle, [buttonIgnore, buttonSave])
                        .then(confirm);
                };
                asksToSave();
            }
            else {
                resolve(true);
            }
        });
        return p;
    };
    EntityDetailViewModelBase.prototype.navigateBack = function () {
        return __awaiter(this, void 0, void 0, function () {
            var result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.canDeactivate()];
                    case 1:
                        result = _a.sent();
                        if (result) {
                            this.doNavigateBack();
                        }
                        return [2];
                }
            });
        });
    };
    EntityDetailViewModelBase.prototype.doNavigateBack = function () {
        if (this.router.history.history.length == 1) {
            this.router.navigate('');
        }
        else {
            this.router.navigateBack();
        }
    };
    EntityDetailViewModelBase.prototype.beforeSave = function () { return new Promise(function (resolve, reject) { resolve(true); }); };
    EntityDetailViewModelBase.prototype.afterSave = function () { return new Promise(function (resolve, reject) { resolve(); }); };
    EntityDetailViewModelBase.prototype.saveCurrentEntity = function (silentSave) {
        return __awaiter(this, void 0, void 0, function () {
            var beforeSaveResult, validationResult, error_1;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.beforeSave()];
                    case 1:
                        beforeSaveResult = _a.sent();
                        if (!(beforeSaveResult == null || beforeSaveResult === true)) return [3, 9];
                        return [4, this.controller.validate({ object: this.entity })];
                    case 2:
                        validationResult = _a.sent();
                        if (!(validationResult.valid === true)) return [3, 8];
                        this.isSaving = true;
                        _a.label = 3;
                    case 3:
                        _a.trys.push([3, 6, , 7]);
                        return [4, this.service.saveEntity(this.entity, silentSave)];
                    case 4:
                        _a.sent();
                        return [4, this.afterSave()];
                    case 5:
                        _a.sent();
                        this.isSaving = false;
                        return [2, this.entity];
                    case 6:
                        error_1 = _a.sent();
                        this.isSaving = false;
                        throw error_1;
                    case 7: return [3, 9];
                    case 8:
                        validationResult.results.forEach(function (r) {
                            _this.logError(r.message, r, (r.message != null));
                        });
                        throw "There are errors";
                    case 9: return [2];
                }
            });
        });
    };
    EntityDetailViewModelBase.prototype.save = function (silentSave, byPassLocking, navigateBack) {
        if (silentSave === void 0) { silentSave = false; }
        if (navigateBack === void 0) { navigateBack = false; }
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.internalSave(silentSave, byPassLocking, navigateBack)];
                    case 1:
                        _a.sent();
                        return [2];
                }
            });
        });
    };
    EntityDetailViewModelBase.prototype.internalSave = function (silentSave, byPassLocking, navigateBack) {
        if (silentSave === void 0) { silentSave = false; }
        if (navigateBack === void 0) { navigateBack = false; }
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.innerSave(silentSave, byPassLocking)];
                    case 1:
                        _a.sent();
                        if (navigateBack === true) {
                            this.doNavigateBack();
                        }
                        else if (this.editingMode === EditingModeEnum.Create) {
                            this.changeRouteAfterCreation();
                        }
                        return [2];
                }
            });
        });
    };
    EntityDetailViewModelBase.prototype.changeRouteAfterCreation = function () {
        if (!this.dialogService.hasOpenDialog) {
            var fragment = this.router.currentInstruction.fragment;
            if (fragment == null || fragment == '') {
                fragment = this.router.baseUrl;
            }
            if (this.router.currentInstruction.queryString != null) {
                fragment += '?' + this.router.currentInstruction.queryString;
            }
            var newRoute = fragment.replace('-100', this.entity.id);
            this.router.navigate(newRoute, { replace: true, trigger: true });
        }
    };
    EntityDetailViewModelBase.prototype.checkInitialized = function () {
        if (!this.isInitialized) {
            this.logError("You must initialize the EntityDetailViewModelBase super object before calling this method", "");
            throw "You must initialize the EntityDetailViewModelBase super object before calling this method";
        }
    };
    EntityDetailViewModelBase.prototype.innerSave = function (silentSave, byPassLocking) {
        var _this = this;
        this.checkInitialized();
        var self = this;
        var p = new Promise(function (resolve, reject) {
            if (_this.isSaving === true) {
                self.logError("general.saveInProgress", null, !silentSave, { ns: "common" });
                reject("Save in progress");
                return;
            }
            if (self.hasChanges === false) {
                self.log("general.nothingToSave", null, !silentSave, { ns: "common" });
                reject("Nothing to save");
                return;
            }
            _this.beforeSave().then(function (beforeSaveResult) {
                if (beforeSaveResult == null || beforeSaveResult === true) {
                    var allChangedEntities = _this.entityManager.manager.getEntities(null, [breeze.EntityState.Added, breeze.EntityState.Modified]);
                    var validateTasks = allChangedEntities.map(function (e) { return _this.controller.validate({ object: e }); });
                    Promise.all(validateTasks).then(function (validationResults) {
                        var notValidResults = validationResults.filter(function (vr) { return vr.valid === false; });
                        if ((notValidResults === null || notValidResults === void 0 ? void 0 : notValidResults.length) == 0) {
                            _this.isSaving = true;
                            _this.service.save(silentSave, byPassLocking)
                                .then(function () {
                                _this.afterSave().then(function () {
                                    resolve(true);
                                }), function (rejectReason) {
                                    _this.logError("Error when saving", rejectReason, true);
                                    reject(rejectReason);
                                };
                            })
                                .catch(function (errors) {
                                reject(errors.message);
                            })
                                .catch(function () { return console.log('Rejection of the Promise'); })
                                .then(function () {
                                _this.isSaving = false;
                            });
                        }
                        else {
                            notValidResults.forEach(function (validationResult) {
                                validationResult.results.forEach(function (r) {
                                    try {
                                        var parsedMessage = JSON.parse(r.message);
                                        if (parsedMessage.Parameters) {
                                            var newParameters = {};
                                            for (var key in parsedMessage.Parameters) {
                                                if (parsedMessage.Parameters.hasOwnProperty(key)) {
                                                    var camelCaseKey = key.charAt(0).toLowerCase() + key.slice(1);
                                                    newParameters[camelCaseKey] = parsedMessage.Parameters[key];
                                                }
                                            }
                                            parsedMessage.Parameters = newParameters;
                                        }
                                        _this.logError(parsedMessage.ErrorMessageTr, r, (parsedMessage.ErrorMessageTr != null), parsedMessage.Parameters);
                                    }
                                    catch (e) {
                                        _this.logError(r.message, r, (r.message != null));
                                    }
                                });
                            });
                            reject("There are errors");
                        }
                    }, function (rejectReason) {
                        _this.logError("Error when saving", rejectReason, true);
                        reject(rejectReason);
                    });
                }
            }), function (rejectReason) {
                _this.logError("Error when saving", rejectReason, true);
                reject(rejectReason);
            };
        });
        return p;
    };
    EntityDetailViewModelBase.prototype.addNew = function () {
        var newRoute = this.router.currentInstruction.config.href;
        if (newRoute != null && !Array.isArray(newRoute)) {
            this.router.navigate(newRoute);
        }
    };
    EntityDetailViewModelBase.prototype.delete = function (detachInverseFKEntities) {
        if (detachInverseFKEntities === void 0) { detachInverseFKEntities = true; }
        return __awaiter(this, void 0, void 0, function () {
            var isDeleted;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.service.deleteEntities([this.entity], detachInverseFKEntities)];
                    case 1:
                        isDeleted = _a.sent();
                        if (isDeleted) {
                            this.detached();
                            this.doNavigateBack();
                        }
                        return [2];
                }
            });
        });
    };
    EntityDetailViewModelBase.prototype.handleShortcuts = function (event) {
        return __awaiter(this, void 0, void 0, function () {
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        if (!(!this.dialogService.hasActiveDialog && (window.navigator.platform.match("Mac") ? event.metaKey : event.ctrlKey) &&
                            (event.key == "s" || event.key == "z"))) return [3, 5];
                        event.stopImmediatePropagation();
                        event.preventDefault();
                        _a = event.key;
                        switch (_a) {
                            case "s": return [3, 1];
                        }
                        return [3, 4];
                    case 1:
                        if (!this.canSave) return [3, 3];
                        return [4, this.save()];
                    case 2:
                        _b.sent();
                        _b.label = 3;
                    case 3: return [3, 4];
                    case 4: return [2, true];
                    case 5: return [2];
                }
            });
        });
    };
    EntityDetailViewModelBase.prototype.detached = function () {
        _super.prototype.detached.call(this);
        this.controller.removeObject(this.entity);
    };
    EntityDetailViewModelBase.prototype.selectAction = function (action) {
        return __awaiter(this, void 0, void 0, function () {
            var promise;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(action.fn != null)) return [3, 2];
                        promise = null;
                        if (typeof action.fn === "function") {
                            promise = action.fn();
                        }
                        else if (typeof action.fn === "string" && this[action.fn] != null) {
                            promise = this[action.fn]();
                        }
                        else {
                            throw new Error("action.fn must be a function or the name of a function on the dialog's view model");
                        }
                        if (!(promise != null)) return [3, 2];
                        if (!(typeof promise.then === "function")) return [3, 2];
                        return [4, promise];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2: return [2];
                }
            });
        });
    };
    __decorate([
        computedFrom("isEditable"),
        __metadata("design:type", Boolean),
        __metadata("design:paramtypes", [])
    ], EntityDetailViewModelBase.prototype, "disabled", null);
    __decorate([
        computedFrom("hasChanges", "isSaving"),
        __metadata("design:type", Boolean),
        __metadata("design:paramtypes", [])
    ], EntityDetailViewModelBase.prototype, "canSave", null);
    __decorate([
        computedFrom("editingMode"),
        __metadata("design:type", Boolean),
        __metadata("design:paramtypes", [])
    ], EntityDetailViewModelBase.prototype, "isCreationMode", null);
    __decorate([
        computedFrom("isCreationMode", "canAdd", "canUpdate"),
        __metadata("design:type", Object),
        __metadata("design:paramtypes", [])
    ], EntityDetailViewModelBase.prototype, "canAddOrUpdate", null);
    __decorate([
        observable,
        __metadata("design:type", Object)
    ], EntityDetailViewModelBase.prototype, "isSaving", void 0);
    __decorate([
        computedFrom("editingMode", "isEditable", "documentTitle", "service"),
        __metadata("design:type", String),
        __metadata("design:paramtypes", [])
    ], EntityDetailViewModelBase.prototype, "ribbonHeaderText", null);
    EntityDetailViewModelBase = __decorate([
        inject(Router, CustomLogger, Config),
        __metadata("design:paramtypes", [Router, CustomLogger])
    ], EntityDetailViewModelBase);
    return EntityDetailViewModelBase;
}(ViewModelBase));

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