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 };
    }
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
import { KebabCase } from './../../../utils/kebab-case';
import { autoinject, BindingEngine, computedFrom, useView } from "aurelia-framework";
import { Router } from "aurelia-router";
import { Actions, EntityTypeNames } from "../../../constants/constants";
import { ServiceBase } from "../../../data/service-base";
import { Various } from "../../../model/common-model";
import { CustomLogger } from "../../../modules/custom-logger";
import { EntityDetailViewModelBase } from "../../detail-view-model-base";
import { EditingModeEnum } from "../../editing-mode-enum";
import { TranslatedPropertyRules } from '../../../utils/translated-property-rules';
import { Datacontext } from "../../../data/data-context";
import { Predicate, FilterQueryOp } from 'breeze-client';
var CrudActions = [Actions.Read, Actions.Create, Actions.Update, Actions.Delete];
export var RoleDetail = (function (_super) {
    __extends(RoleDetail, _super);
    function RoleDetail(router, logger, datacontext, bindingEngine) {
        var _this = _super.call(this, router, logger) || this;
        _this.bindingEngine = bindingEngine;
        _this.ressourceName = EntityTypeNames.Role;
        _this.selectedLanguageCode = 'en';
        _this.canUpdateUser = false;
        _this.filter = {
            active: false,
            searchGroup: null,
            searchName: null,
            showScreens: false,
            showFunctionalities: false,
            showAssigned: true,
            showUnassigned: false,
        };
        _this.isLoading = true;
        _this.addObserver = function (observed, toSet) {
            _this.disposables.push(_this.bindingEngine.propertyObserver(observed, "isSelected").subscribe(function (newVal) {
                if (_this.isLoading == false && newVal) {
                    toSet.isSelected = true;
                }
            }));
        };
        _this.filterFn = function (group) {
            var _a, _b, _c, _d;
            var keep = true;
            if (_this.filter.showFunctionalities != _this.filter.showScreens) {
                if (_this.filter.showFunctionalities) {
                    keep = group.type == 'functionality';
                }
                else {
                    keep = group.type == 'screen';
                }
            }
            keep = keep && ((_this.filter.showAssigned && group.isAnySelected)
                || (_this.filter.showUnassigned && false == group.isAnySelected));
            if (((_a = _this.filter.searchName) === null || _a === void 0 ? void 0 : _a.length) > 0) {
                keep = keep && ((_b = group.translatedName) === null || _b === void 0 ? void 0 : _b.length) > 0 && group.translatedName.toLocaleLowerCase().includes(_this.filter.searchName.toLocaleLowerCase());
            }
            if (((_c = _this.filter.searchGroup) === null || _c === void 0 ? void 0 : _c.length) > 0) {
                keep = keep && ((_d = group.translatedHierarchy) === null || _d === void 0 ? void 0 : _d.length) > 0 && group.translatedHierarchy.toLocaleLowerCase().includes(_this.filter.searchGroup.toLocaleLowerCase());
            }
            return keep;
        };
        _super.prototype.initialize.call(_this, new ServiceBase(EntityTypeNames.Role));
        _this.selectedLanguageCode = datacontext.currentLanguage.code;
        _this.rolePermissionService = new ServiceBase(EntityTypeNames.RolePermission, null, EntityTypeNames.ResourceNames.RolePermission);
        _this.userRoleService = new ServiceBase(EntityTypeNames.UserRole, null, EntityTypeNames.ResourceNames.UserRole);
        _this.userService = new ServiceBase(EntityTypeNames.User, null, EntityTypeNames.ResourceNames.User);
        _this.userService.gridDataSource.customSelect2Predicates = function () {
            var _a, _b;
            var predicate = new Predicate('disabled', FilterQueryOp.Equals, false);
            if (((_b = (_a = _this.entity) === null || _a === void 0 ? void 0 : _a.users) === null || _b === void 0 ? void 0 : _b.length) > 0) {
                return predicate.and.apply(predicate, __spreadArray([], __read(_this.entity.users.map(function (x) { return new Predicate('id', FilterQueryOp.NotEquals, x.userId); })), false));
            }
            return predicate;
        };
        return _this;
    }
    RoleDetail.prototype.getTranslationKeyEntityTypeName = function () {
        return 'common:' + _super.prototype.getTranslationKeyEntityTypeName.call(this);
    };
    Object.defineProperty(RoleDetail.prototype, "documentTitle", {
        get: function () {
            var _a, _b;
            if (this.editingMode === EditingModeEnum.Create) {
                return this.i18n.tr('common:role.role');
            }
            else if (this.editingMode === EditingModeEnum.Update) {
                return (_b = (_a = this.entity) === null || _a === void 0 ? void 0 : _a.name) === null || _b === void 0 ? void 0 : _b._translation;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RoleDetail.prototype, "crudActions", {
        get: function () {
            return CrudActions;
        },
        enumerable: false,
        configurable: true
    });
    RoleDetail.prototype.bind = function () {
        var _a, _b, _c, _d, _e;
        var userResource = (_e = (_d = (_c = (_b = (_a = this.router) === null || _a === void 0 ? void 0 : _a.currentInstruction) === null || _b === void 0 ? void 0 : _b.config) === null || _c === void 0 ? void 0 : _c.settings) === null || _d === void 0 ? void 0 : _d.params) === null || _e === void 0 ? void 0 : _e.userResource;
        this.canUpdateUser = this.authService.checkAccess(userResource !== null && userResource !== void 0 ? userResource : EntityTypeNames.User, Actions.Update);
    };
    RoleDetail.prototype.activate = function (params) {
        return __awaiter(this, void 0, void 0, function () {
            var id, _a, _b;
            var _c;
            var _this = this;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        this.isLoading = true;
                        return [4, _super.prototype.activate.call(this, params)];
                    case 1:
                        _d.sent();
                        return [4, this.loadPermissions()];
                    case 2:
                        _d.sent();
                        return [4, this.addObservableOnPermissions()];
                    case 3:
                        _d.sent();
                        id = params.param1;
                        if (!(id == Various.NewId)) return [3, 7];
                        this.editingMode = EditingModeEnum.Create;
                        _a = this;
                        return [4, this.service.createEntity()];
                    case 4:
                        _a.entity = _d.sent();
                        this.entity.active = true;
                        if (!(params.duplicateFrom != null)) return [3, 6];
                        return [4, this.loadRole(params.duplicateFrom)];
                    case 5:
                        _d.sent();
                        _d.label = 6;
                    case 6:
                        this.filter.showUnassigned = true;
                        return [3, 9];
                    case 7:
                        this.editingMode = EditingModeEnum.Update;
                        _b = this;
                        return [4, this.loadRole(id, ['users.user'])];
                    case 8:
                        _b.entity = _d.sent();
                        _d.label = 9;
                    case 9:
                        this.controller.addObject(this.entity);
                        TranslatedPropertyRules.anyRequired('name')
                            .ensure('users').satisfies(function (userRoles) { return userRoles.every(function (x) { return x.userId > 0; }); }).when(function () { return false == _this.isCreationMode; })
                            .on(this.entity);
                        this.isLoading = false;
                        (_c = this.disposables).push.apply(_c, __spreadArray([], __read(Object.keys(this.filter).map(function (prop) {
                            return _this.bindingEngine.propertyObserver(_this.filter, prop)
                                .subscribe(function () { var _a; return (_a = _this.permissionsTableElement) === null || _a === void 0 ? void 0 : _a.filterChanged(); });
                        })), false));
                        return [2];
                }
            });
        });
    };
    RoleDetail.prototype.loadRole = function (id, expands) {
        if (expands === void 0) { expands = []; }
        return __awaiter(this, void 0, void 0, function () {
            var role;
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        expands.push('permissions');
                        return [4, (_a = this.service).getEntityById.apply(_a, __spreadArray([id], __read(expands), false))];
                    case 1:
                        role = _b.sent();
                        this.permissionGroups.forEach(function (group) {
                            return group.permissions.forEach(function (permission) {
                                return permission.isSelected = role.permissions.find(function (x) { return x.permissionId == permission.permissionId; }) != null;
                            });
                        });
                        return [2, role];
                }
            });
        });
    };
    RoleDetail.prototype.loadPermissions = function () {
        return __awaiter(this, void 0, void 0, function () {
            var permissionModels, permissions, groupsUsingCustomConfig;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, new ServiceBase(EntityTypeNames.Permission, null, EntityTypeNames.ResourceNames.Permission)
                            .getEntities(null, null, null, { propertyPaths: 'permissionId' })];
                    case 1:
                        permissionModels = _a.sent();
                        permissions = permissionModels.map(function (x) { return new Permission(x); });
                        this.permissionGroups = [];
                        permissions.groupBy('context').forEach(function (permissions) {
                            var _a;
                            return (_a = _this.permissionGroups).push.apply(_a, __spreadArray([], __read(__spreadArray(__spreadArray([], __read(permissions.filter(function (x) { return false == x.isCrud; }).map(function (x) { return new PermissionGroup(_this, [x]); })), false), [
                                new CrudPermissionGroup(_this, permissions.filter(function (x) { return x.isCrud; }))
                            ], false).filter(function (group) { return group.permissions.length > 0; })), false));
                        });
                        groupsUsingCustomConfig = [];
                        this.permissionGroups.forEach(function (group) {
                            var _a, _b, _c, _d, _e;
                            var route = _this.router.navigation.find(function (x) {
                                var _a, _b;
                                var matchesContext = ((_a = x.settings) === null || _a === void 0 ? void 0 : _a.resource) != null && KebabCase.fromCamelCase(x.settings.resource) == group.context;
                                if (false == matchesContext) {
                                    return false;
                                }
                                if (group.isCrud && ((_b = x.settings) === null || _b === void 0 ? void 0 : _b.action) == null) {
                                    return true;
                                }
                                var routeActions = isArray(x.settings.action) ? x.settings.action : [x.settings.action];
                                return group.permissions.some(function (p) { return routeActions.some(function (a) { return p.action == a; }); });
                            });
                            var config = (_b = (_a = _this.config.permissionsConfig) === null || _a === void 0 ? void 0 : _a.perContext) === null || _b === void 0 ? void 0 : _b.find(function (x) {
                                var _a, _b;
                                return (x.context != null || (((_a = route === null || route === void 0 ? void 0 : route.config) === null || _a === void 0 ? void 0 : _a.name) != null && x.routeName == null))
                                    && (x.context == null || KebabCase.fromCamelCase(x.context) == group.context)
                                    && (x.routeName == null || ((_b = route === null || route === void 0 ? void 0 : route.config) === null || _b === void 0 ? void 0 : _b.name) == null || x.routeName == route.config.name);
                            });
                            if (config != null || route != null) {
                                group.qualifiedName = Object.assign([], (_c = config === null || config === void 0 ? void 0 : config.qualifiedName) !== null && _c !== void 0 ? _c : _this.makeQualifiedName(route));
                                group.href = (_d = config === null || config === void 0 ? void 0 : config.href) !== null && _d !== void 0 ? _d : (route == null ? null : ('/' + route.relativeHref));
                                group.hint = config === null || config === void 0 ? void 0 : config.hint;
                                if (config != null) {
                                    group.isCrud = (_e = config.isCrud) !== null && _e !== void 0 ? _e : group.isCrud;
                                    group.forceType = config.forceType;
                                    if (false == group.isCrud) {
                                        group.qualifiedName.push(_this.config.permissionsConfig.permissionNames[group.context][group.firstPermission.action]);
                                    }
                                    groupsUsingCustomConfig.push(group);
                                }
                                else if (route) {
                                    group.additionalScreens = _this.router.navigation
                                        .filter(function (x) { var _a, _b; return ((_a = x.settings) === null || _a === void 0 ? void 0 : _a.resource) == route.settings.resource && x != route && (((_b = x.settings) === null || _b === void 0 ? void 0 : _b.action) == null || group.permissions.some(function (p) { var _a; return p.action == ((_a = x.settings) === null || _a === void 0 ? void 0 : _a.action); })); })
                                        .map(function (x) {
                                        var screen = new GroupBase();
                                        screen.qualifiedName = _this.makeQualifiedName(x);
                                        screen.href = '/' + x.relativeHref;
                                        return screen;
                                    });
                                }
                            }
                            else {
                                console.warn('No menu found for ' + group.context);
                                group.qualifiedName.push(group.context);
                            }
                        });
                        groupsUsingCustomConfig.filter(function (x) { return false == x.isCrud; }).forEach(function (group) {
                            var customCrudGroup = groupsUsingCustomConfig.find(function (x) { return x.context == group.context && x.isCrud && x != group; });
                            if (customCrudGroup != null) {
                                group.qualifiedName = __spreadArray(__spreadArray([], __read(customCrudGroup.hierarchy), false), [group.name], false);
                            }
                        });
                        this.sortGroups(this.permissionGroups);
                        return [2];
                }
            });
        });
    };
    RoleDetail.prototype.makeQualifiedName = function (route) {
        var qualifiedName = [route.title];
        if (route.settings.subGroup) {
            qualifiedName.push(route.settings.subGroup, route.settings.group);
        }
        else if (this.router.navigation.some(function (x) { var _a; return ((_a = x.settings) === null || _a === void 0 ? void 0 : _a.resource) != route.settings.resource && x.settings.group == route.settings.group; })) {
            qualifiedName.push(route.settings.group);
        }
        return qualifiedName.reverse();
    };
    RoleDetail.prototype.sortGroups = function (groups) {
        var _this = this;
        groups.sort(function (a, b) {
            var _a, _b;
            for (var i = 0; i < a.qualifiedName.length && i < b.qualifiedName.length; ++i) {
                var strA = (_a = _this.i18n.tr(a.qualifiedName[i])) !== null && _a !== void 0 ? _a : a.qualifiedName[i];
                var strB = (_b = _this.i18n.tr(b.qualifiedName[i])) !== null && _b !== void 0 ? _b : b.qualifiedName[i];
                var compare = strA.toLocaleLowerCase().localeCompare(strB.toLocaleLowerCase());
                if (compare != 0) {
                    return compare;
                }
            }
            return a.qualifiedName.length - b.qualifiedName.length;
        });
    };
    RoleDetail.prototype.addObservableOnPermissions = function () {
        var _this = this;
        this.permissionGroups.filter(function (x) { return x.isCrud; }).forEach(function (x) {
            var group = x;
            if (group.deletePermission && group.readPermission) {
                _this.addObserver(group.deletePermission, group.readPermission);
            }
            if (group.updatePermission) {
                if (group.readPermission) {
                    _this.addObserver(group.updatePermission, group.readPermission);
                }
                if (group.createPermission) {
                    _this.addObserver(group.createPermission, group.updatePermission);
                }
            }
        });
    };
    RoleDetail.prototype.toggleFilter = function () {
        this.filter.active = !this.filter.active;
        if (false == this.filter.active) {
            this.filter.searchGroup = null;
            this.filter.searchName = null;
            this.filter.showScreens = false;
            this.filter.showFunctionalities = false;
        }
    };
    RoleDetail.prototype.toggleTypeFilter = function (type) {
        this.filter[type] = !this.filter[type];
    };
    Object.defineProperty(RoleDetail.prototype, "filteredPermissionGroups", {
        get: function () {
            var _this = this;
            return this.permissionGroups
                .filter(function (group) {
                if (_this.filter.showFunctionalities == _this.filter.showScreens) {
                    return true;
                }
                else if (_this.filter.showFunctionalities) {
                    return false == group.isCrud;
                }
                else {
                    return group.isCrud;
                }
            })
                .filter(function (group) {
                if (_this.filter.showAssigned && group.isAnySelected) {
                    return true;
                }
                if (_this.filter.showUnassigned && false == group.isAnySelected) {
                    return true;
                }
                return false;
            });
        },
        enumerable: false,
        configurable: true
    });
    RoleDetail.prototype.isSelectClicked = function (permission) {
        if (false == this.isLoading) {
            this.hasChanges = true;
        }
    };
    RoleDetail.prototype.beforeSave = function () {
        return __awaiter(this, void 0, void 0, function () {
            var assignedPermissionsMap, i, rolePermission;
            var _this = this;
            return __generator(this, function (_a) {
                assignedPermissionsMap = this.permissionGroups.reduce(function (result, group) {
                    group.permissions.filter(function (p) { return p.isSelected; }).forEach(function (p) { return result[p.permissionId] = true; });
                    return result;
                }, {});
                for (i = this.entity.permissions.length - 1; i >= 0; --i) {
                    rolePermission = this.entity.permissions[i];
                    if (assignedPermissionsMap[rolePermission.permissionId] == null) {
                        rolePermission.entityAspect.setDeleted();
                    }
                    else {
                        assignedPermissionsMap[rolePermission.permissionId] = false;
                    }
                }
                ;
                Object.keys(assignedPermissionsMap)
                    .filter(function (permissionId) { return assignedPermissionsMap[permissionId] === true; })
                    .forEach(function (permissionId) { return _this.rolePermissionService.createEntity({ roleId: _this.entity.id, permissionId: permissionId }, true); });
                return [2];
            });
        });
    };
    Object.defineProperty(RoleDetail.prototype, "canAddUser", {
        get: function () {
            return this.newUserRole == null;
        },
        enumerable: false,
        configurable: true
    });
    RoleDetail.prototype.addUser = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        if (!this.canAddUser) return [3, 2];
                        _a = this;
                        return [4, this.userRoleService.createEntity({ roleId: -1 })];
                    case 1:
                        _a.newUserRole = _b.sent();
                        _b.label = 2;
                    case 2: return [2];
                }
            });
        });
    };
    RoleDetail.prototype.cancelAddUser = function () {
        var _a;
        (_a = this.newUserRole) === null || _a === void 0 ? void 0 : _a.entityAspect.setDetached();
        this.newUserRole = null;
    };
    Object.defineProperty(RoleDetail.prototype, "canApplyAddUser", {
        get: function () {
            var _a;
            return ((_a = this.newUserRole) === null || _a === void 0 ? void 0 : _a.userId) > 0;
        },
        enumerable: false,
        configurable: true
    });
    RoleDetail.prototype.applyAddUser = function () {
        if (this.canApplyAddUser) {
            var newRole = this.newUserRole;
            this.newUserRole = null;
            var existing = this.userRoleService.manager.getEntityByKey(EntityTypeNames.UserRole, [newRole.userId, this.entity.id]);
            if (existing === null || existing === void 0 ? void 0 : existing.entityAspect.entityState.isDeleted()) {
                newRole.entityAspect.rejectChanges();
                existing.entityAspect.rejectChanges();
            }
            else {
                newRole.roleId = this.entity.id;
            }
        }
    };
    RoleDetail.prototype.removeUser = function (userRole) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                if (userRole.entityAspect.entityState.isAdded()) {
                    userRole.entityAspect.setDetached();
                }
                else {
                    userRole.entityAspect.setDeleted();
                }
                return [2];
            });
        });
    };
    __decorate([
        computedFrom('editingMode', 'entity.name._translation'),
        __metadata("design:type", Object),
        __metadata("design:paramtypes", [])
    ], RoleDetail.prototype, "documentTitle", null);
    __decorate([
        computedFrom('ressourceName'),
        __metadata("design:type", Array),
        __metadata("design:paramtypes", [])
    ], RoleDetail.prototype, "crudActions", null);
    __decorate([
        computedFrom('filter.showScreens', 'filter.showFunctionalities', 'filter.showAssigned', 'filter.showUnassigned'),
        __metadata("design:type", Array),
        __metadata("design:paramtypes", [])
    ], RoleDetail.prototype, "filteredPermissionGroups", null);
    __decorate([
        computedFrom('newUserRole'),
        __metadata("design:type", Boolean),
        __metadata("design:paramtypes", [])
    ], RoleDetail.prototype, "canAddUser", null);
    __decorate([
        computedFrom('newUserRole.userId'),
        __metadata("design:type", Boolean),
        __metadata("design:paramtypes", [])
    ], RoleDetail.prototype, "canApplyAddUser", null);
    RoleDetail = __decorate([
        autoinject,
        useView("./../../../vm/security/roles/role-detail.html"),
        __metadata("design:paramtypes", [Router, CustomLogger, Datacontext, BindingEngine])
    ], RoleDetail);
    return RoleDetail;
}(EntityDetailViewModelBase));
var Permission = (function () {
    function Permission(permission) {
        var split = permission.permissionId.split(':');
        this.action = split[0];
        this.context = split[1];
        this._isSelected = false;
        this._isLocked = permission.isLocked;
    }
    Object.defineProperty(Permission.prototype, "isSelected", {
        get: function () {
            return this._isSelected;
        },
        set: function (value) {
            var _a, _b;
            this._isSelected = value;
            (_b = (_a = this.group) === null || _a === void 0 ? void 0 : _a.vm) === null || _b === void 0 ? void 0 : _b.isSelectClicked(this);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Permission.prototype, "isLocked", {
        get: function () {
            return this._isLocked;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Permission.prototype, "permissionId", {
        get: function () {
            return "".concat(this.action, ":").concat(this.context);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Permission.prototype, "isCrud", {
        get: function () {
            var _this = this;
            return CrudActions.find(function (x) { return x == _this.action; }) != null;
        },
        enumerable: false,
        configurable: true
    });
    __decorate([
        computedFrom('_isSelected'),
        __metadata("design:type", Boolean),
        __metadata("design:paramtypes", [Boolean])
    ], Permission.prototype, "isSelected", null);
    __decorate([
        computedFrom('_isLocked'),
        __metadata("design:type", Object),
        __metadata("design:paramtypes", [])
    ], Permission.prototype, "isLocked", null);
    __decorate([
        computedFrom('action', 'context'),
        __metadata("design:type", String),
        __metadata("design:paramtypes", [])
    ], Permission.prototype, "permissionId", null);
    __decorate([
        computedFrom('action'),
        __metadata("design:type", Boolean),
        __metadata("design:paramtypes", [])
    ], Permission.prototype, "isCrud", null);
    return Permission;
}());
var GroupBase = (function () {
    function GroupBase() {
        this.qualifiedName = [];
    }
    Object.defineProperty(GroupBase.prototype, "name", {
        get: function () {
            var _a;
            return (_a = this.qualifiedName) === null || _a === void 0 ? void 0 : _a.last();
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(GroupBase.prototype, "hierarchy", {
        get: function () {
            var _a;
            return (_a = this.qualifiedName) === null || _a === void 0 ? void 0 : _a.slice(0, -1);
        },
        enumerable: false,
        configurable: true
    });
    __decorate([
        computedFrom('qualifiedName.length'),
        __metadata("design:type", String),
        __metadata("design:paramtypes", [])
    ], GroupBase.prototype, "name", null);
    __decorate([
        computedFrom('qualifiedName.length'),
        __metadata("design:type", Array),
        __metadata("design:paramtypes", [])
    ], GroupBase.prototype, "hierarchy", null);
    return GroupBase;
}());
var PermissionGroup = (function (_super) {
    __extends(PermissionGroup, _super);
    function PermissionGroup(vm, permissions) {
        var _this = _super.call(this) || this;
        _this.vm = vm;
        _this.permissions = permissions;
        _this.additionalScreens = [];
        permissions.forEach(function (x) { return x.group = _this; });
        _this.isCrud = false;
        return _this;
    }
    Object.defineProperty(PermissionGroup.prototype, "isAnySelected", {
        get: function () {
            return this.permissions.find(function (x) { return x.isSelected; }) != null;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(PermissionGroup.prototype, "type", {
        get: function () {
            var _a;
            return (_a = this.forceType) !== null && _a !== void 0 ? _a : (this.isCrud ? 'screen' : 'functionality');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(PermissionGroup.prototype, "firstPermission", {
        get: function () {
            return this.permissions[0];
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(PermissionGroup.prototype, "context", {
        get: function () {
            return this.firstPermission.context;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(PermissionGroup.prototype, "translatedName", {
        get: function () {
            return this.vm.i18n.tr(this.name);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(PermissionGroup.prototype, "translatedHierarchy", {
        get: function () {
            var _this = this;
            var _a;
            return (_a = this.hierarchy) === null || _a === void 0 ? void 0 : _a.map(function (x) { return _this.vm.i18n.tr(x); }).join(' ');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(PermissionGroup.prototype, "isLocked", {
        get: function () {
            var _a;
            return ((_a = this.vm.entity) === null || _a === void 0 ? void 0 : _a.isLocked) || this.permissions.some(function (x) { return x.isLocked; });
        },
        enumerable: false,
        configurable: true
    });
    __decorate([
        computedFrom('forceType', 'isCrud'),
        __metadata("design:type", String),
        __metadata("design:paramtypes", [])
    ], PermissionGroup.prototype, "type", null);
    __decorate([
        computedFrom('permissions[0]'),
        __metadata("design:type", Permission),
        __metadata("design:paramtypes", [])
    ], PermissionGroup.prototype, "firstPermission", null);
    __decorate([
        computedFrom('firstPermission.context'),
        __metadata("design:type", String),
        __metadata("design:paramtypes", [])
    ], PermissionGroup.prototype, "context", null);
    __decorate([
        computedFrom('name'),
        __metadata("design:type", String),
        __metadata("design:paramtypes", [])
    ], PermissionGroup.prototype, "translatedName", null);
    __decorate([
        computedFrom('hierarchy.length'),
        __metadata("design:type", String),
        __metadata("design:paramtypes", [])
    ], PermissionGroup.prototype, "translatedHierarchy", null);
    return PermissionGroup;
}(GroupBase));
var CrudPermissionGroup = (function (_super) {
    __extends(CrudPermissionGroup, _super);
    function CrudPermissionGroup(vm, permissions) {
        var _this = _super.call(this, vm, permissions) || this;
        _this.vm = vm;
        permissions.forEach(function (p) { return _this[p.action + "Permission"] = p; });
        _this.isCrud = true;
        return _this;
    }
    return CrudPermissionGroup;
}(PermissionGroup));

//# sourceMappingURL=role-detail.js.map
