"use strict";
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 (_) 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 };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DBHelper = void 0;
var Crypt_1 = require("./Crypt");
var openflow_api_1 = require("@openiap/openflow-api");
var Config_1 = require("./Config");
var DBHelper = /** @class */ (function () {
    function DBHelper() {
    }
    DBHelper.FindByUsername = function (username, jwt) {
        if (jwt === void 0) { jwt = null; }
        return __awaiter(this, void 0, void 0, function () {
            var byuser, byid, q, items, result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        byuser = { username: new RegExp(["^", username, "$"].join(""), "i") };
                        byid = { federationids: new RegExp(["^", username, "$"].join(""), "i") };
                        q = { $or: [byuser, byid] };
                        if (jwt === null || jwt == undefined || jwt == "") {
                            jwt = Crypt_1.Crypt.rootToken();
                        }
                        return [4 /*yield*/, Config_1.Config.db.query(q, null, 1, 0, null, "users", jwt)];
                    case 1:
                        items = _a.sent();
                        if (items === null || items === undefined || items.length === 0) {
                            return [2 /*return*/, null];
                        }
                        result = openflow_api_1.User.assign(items[0]);
                        return [4 /*yield*/, this.DecorateWithRoles(result)];
                    case 2:
                        _a.sent();
                        return [2 /*return*/, result];
                }
            });
        });
    };
    DBHelper.FindById = function (_id, jwt) {
        if (jwt === void 0) { jwt = null; }
        return __awaiter(this, void 0, void 0, function () {
            var items, result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (jwt === null || jwt == undefined || jwt == "") {
                            jwt = Crypt_1.Crypt.rootToken();
                        }
                        return [4 /*yield*/, Config_1.Config.db.query({ _id: _id }, null, 1, 0, null, "users", jwt)];
                    case 1:
                        items = _a.sent();
                        if (items === null || items === undefined || items.length === 0) {
                            return [2 /*return*/, null];
                        }
                        result = openflow_api_1.User.assign(items[0]);
                        return [4 /*yield*/, this.DecorateWithRoles(result)];
                    case 2:
                        _a.sent();
                        return [2 /*return*/, result];
                }
            });
        });
    };
    DBHelper.FindByUsernameOrId = function (username, id) {
        return __awaiter(this, void 0, void 0, function () {
            var items, result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, Config_1.Config.db.query({ $or: [{ username: new RegExp(["^", username, "$"].join(""), "i") }, { _id: id }] }, null, 1, 0, null, "users", Crypt_1.Crypt.rootToken())];
                    case 1:
                        items = _a.sent();
                        if (items === null || items === undefined || items.length === 0) {
                            return [2 /*return*/, null];
                        }
                        result = openflow_api_1.User.assign(items[0]);
                        return [4 /*yield*/, this.DecorateWithRoles(result)];
                    case 2:
                        _a.sent();
                        return [2 /*return*/, result];
                }
            });
        });
    };
    DBHelper.FindByUsernameOrFederationid = function (username) {
        return __awaiter(this, void 0, void 0, function () {
            var byuser, byid, q, items, result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        byuser = { username: new RegExp(["^", username, "$"].join(""), "i") };
                        byid = { federationids: new RegExp(["^", username, "$"].join(""), "i") };
                        q = { $or: [byuser, byid] };
                        return [4 /*yield*/, Config_1.Config.db.query(q, null, 1, 0, null, "users", Crypt_1.Crypt.rootToken())];
                    case 1:
                        items = _a.sent();
                        if (items === null || items === undefined || items.length === 0) {
                            return [2 /*return*/, null];
                        }
                        result = openflow_api_1.User.assign(items[0]);
                        return [4 /*yield*/, this.DecorateWithRoles(result)];
                    case 2:
                        _a.sent();
                        return [2 /*return*/, result];
                }
            });
        });
    };
    DBHelper.GetRoles = function (_id, ident) {
        return __awaiter(this, void 0, void 0, function () {
            var result, query, ids, _roles, i, role, _subroles, y, subrole;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (ident > Config_1.Config.max_recursive_group_depth)
                            return [2 /*return*/, []];
                        result = [];
                        query = { "members": { "$elemMatch": { _id: _id } } };
                        ids = [];
                        return [4 /*yield*/, Config_1.Config.db.query(query, null, Config_1.Config.expected_max_roles, 0, null, "users", Crypt_1.Crypt.rootToken())];
                    case 1:
                        _roles = _a.sent();
                        i = 0;
                        _a.label = 2;
                    case 2:
                        if (!(i < _roles.length)) return [3 /*break*/, 5];
                        role = _roles[i];
                        if (!(ids.indexOf(role._id) == -1)) return [3 /*break*/, 4];
                        ids.push(role._id);
                        result.push(role);
                        console.log(role.name + " " + role._id);
                        return [4 /*yield*/, this.GetRoles(role._id, ident + 1)];
                    case 3:
                        _subroles = _a.sent();
                        for (y = 0; y < _subroles.length; y++) {
                            subrole = _subroles[y];
                            console.log(role.name + " " + subrole.name + " " + subrole._id);
                            if (ids.indexOf(subrole._id) == -1) {
                                ids.push(subrole._id);
                                result.push(subrole);
                            }
                        }
                        _a.label = 4;
                    case 4:
                        i++;
                        return [3 /*break*/, 2];
                    case 5: return [2 /*return*/, result];
                }
            });
        });
    };
    DBHelper.DecorateWithRoles = function (user) {
        return __awaiter(this, void 0, void 0, function () {
            var roles, query, _roles_1, foundone_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!!Config_1.Config.decorate_roles_fetching_all_roles) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.GetRoles(user._id, 0)];
                    case 1:
                        roles = _a.sent();
                        user.roles = [];
                        roles.forEach(function (role) {
                            user.roles.push(new openflow_api_1.Rolemember(role.name, role._id));
                        });
                        return [3 /*break*/, 4];
                    case 2:
                        query = { _type: "role" };
                        return [4 /*yield*/, Config_1.Config.db.query(query, null, Config_1.Config.expected_max_roles, 0, null, "users", Crypt_1.Crypt.rootToken())];
                    case 3:
                        _roles_1 = _a.sent();
                        if (_roles_1.length === 0 && user.username !== "root") {
                            throw new Error("System has no roles !!!!!!");
                        }
                        user.roles = [];
                        _roles_1.forEach(function (role) {
                            var isMember = -1;
                            if (role.members !== undefined) {
                                isMember = role.members.map(function (e) { return e._id; }).indexOf(user._id);
                            }
                            var beenAdded = user.roles.map(function (e) { return e._id; }).indexOf(user._id);
                            if (isMember > -1 && beenAdded === -1) {
                                user.roles.push(new openflow_api_1.Rolemember(role.name, role._id));
                            }
                        });
                        foundone_1 = true;
                        while (foundone_1) {
                            foundone_1 = false;
                            user.roles.forEach(function (userrole) {
                                _roles_1.forEach(function (role) {
                                    var isMember = -1;
                                    if (role.members !== undefined) {
                                        isMember = role.members.map(function (e) { return e._id; }).indexOf(userrole._id);
                                    }
                                    var beenAdded = user.roles.map(function (e) { return e._id; }).indexOf(role._id);
                                    if (isMember > -1 && beenAdded === -1) {
                                        user.roles.push(new openflow_api_1.Rolemember(role.name, role._id));
                                        foundone_1 = true;
                                    }
                                });
                            });
                        }
                        _a.label = 4;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    DBHelper.FindRoleByName = function (name) {
        return __awaiter(this, void 0, void 0, function () {
            var items, result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, Config_1.Config.db.query({ name: name }, null, 1, 0, null, "users", Crypt_1.Crypt.rootToken())];
                    case 1:
                        items = _a.sent();
                        if (items === null || items === undefined || items.length === 0) {
                            return [2 /*return*/, null];
                        }
                        result = openflow_api_1.Role.assign(items[0]);
                        return [2 /*return*/, result];
                }
            });
        });
    };
    DBHelper.FindRoleByNameOrId = function (name, id) {
        return __awaiter(this, void 0, void 0, function () {
            var jwt, items, result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        jwt = Crypt_1.Crypt.rootToken();
                        return [4 /*yield*/, Config_1.Config.db.query({ $or: [{ name: name }, { _id: id }] }, null, 1, 0, null, "users", jwt)];
                    case 1:
                        items = _a.sent();
                        if (items === null || items === undefined || items.length === 0) {
                            return [2 /*return*/, null];
                        }
                        result = openflow_api_1.Role.assign(items[0]);
                        return [2 /*return*/, result];
                }
            });
        });
    };
    DBHelper.Save = function (item, jwt) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, Config_1.Config.db._UpdateOne(null, item, "users", 0, false, jwt)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    DBHelper.EnsureRole = function (jwt, name, id) {
        return __awaiter(this, void 0, void 0, function () {
            var role;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.FindRoleByNameOrId(name, id)];
                    case 1:
                        role = _a.sent();
                        if (role !== null && (role._id === id || id === null)) {
                            return [2 /*return*/, role];
                        }
                        if (!(role !== null && !openflow_api_1.NoderedUtil.IsNullEmpty(role._id))) return [3 /*break*/, 3];
                        return [4 /*yield*/, Config_1.Config.db.DeleteOne(role._id, "users", jwt)];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3:
                        role = new openflow_api_1.Role();
                        role.name = name;
                        role._id = id;
                        return [4 /*yield*/, Config_1.Config.db.InsertOne(role, "users", 0, false, jwt)];
                    case 4:
                        role = _a.sent();
                        role = openflow_api_1.Role.assign(role);
                        openflow_api_1.Base.addRight(role, openflow_api_1.WellknownIds.admins, "admins", [openflow_api_1.Rights.full_control]);
                        openflow_api_1.Base.addRight(role, role._id, role.name, [openflow_api_1.Rights.full_control]);
                        openflow_api_1.Base.removeRight(role, role._id, [openflow_api_1.Rights.delete]);
                        return [4 /*yield*/, this.Save(role, jwt)];
                    case 5:
                        _a.sent();
                        return [2 /*return*/, openflow_api_1.Role.assign(role)];
                }
            });
        });
    };
    DBHelper.ensureUser = function (jwt, name, username, id, password) {
        return __awaiter(this, void 0, void 0, function () {
            var user, users, name_1, noderedadmins;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.FindByUsernameOrId(username, id)];
                    case 1:
                        user = _a.sent();
                        if (user !== null && (user._id === id || id === null)) {
                            return [2 /*return*/, user];
                        }
                        if (!(user !== null && id !== null)) return [3 /*break*/, 3];
                        return [4 /*yield*/, Config_1.Config.db.DeleteOne(user._id, "users", jwt)];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3:
                        user = new openflow_api_1.User();
                        user._id = id;
                        user.name = name;
                        user.username = username;
                        if (!(password !== null && password !== undefined && password !== "")) return [3 /*break*/, 5];
                        return [4 /*yield*/, Crypt_1.Crypt.SetPassword(user, password)];
                    case 4:
                        _a.sent();
                        return [3 /*break*/, 7];
                    case 5: return [4 /*yield*/, Crypt_1.Crypt.SetPassword(user, Math.random().toString(36).substr(2, 9))];
                    case 6:
                        _a.sent();
                        _a.label = 7;
                    case 7: return [4 /*yield*/, Config_1.Config.db.InsertOne(user, "users", 0, false, jwt)];
                    case 8:
                        user = _a.sent();
                        user = openflow_api_1.User.assign(user);
                        openflow_api_1.Base.addRight(user, openflow_api_1.WellknownIds.admins, "admins", [openflow_api_1.Rights.full_control]);
                        openflow_api_1.Base.addRight(user, user._id, user.name, [openflow_api_1.Rights.full_control]);
                        openflow_api_1.Base.removeRight(user, user._id, [openflow_api_1.Rights.delete]);
                        return [4 /*yield*/, this.Save(user, jwt)];
                    case 9:
                        _a.sent();
                        return [4 /*yield*/, this.FindRoleByName("users")];
                    case 10:
                        users = _a.sent();
                        users.AddMember(user);
                        if (!Config_1.Config.auto_create_personal_nodered_group) return [3 /*break*/, 13];
                        name_1 = user.username;
                        name_1 = name_1.split("@").join("").split(".").join("");
                        name_1 = name_1.toLowerCase();
                        return [4 /*yield*/, this.EnsureRole(jwt, name_1 + "noderedadmins", null)];
                    case 11:
                        noderedadmins = _a.sent();
                        openflow_api_1.Base.addRight(noderedadmins, user._id, user.username, [openflow_api_1.Rights.full_control]);
                        openflow_api_1.Base.removeRight(noderedadmins, user._id, [openflow_api_1.Rights.delete]);
                        noderedadmins.AddMember(user);
                        return [4 /*yield*/, this.Save(noderedadmins, jwt)];
                    case 12:
                        _a.sent();
                        _a.label = 13;
                    case 13: return [4 /*yield*/, this.Save(users, jwt)];
                    case 14:
                        _a.sent();
                        return [4 /*yield*/, this.DecorateWithRoles(user)];
                    case 15:
                        _a.sent();
                        return [2 /*return*/, user];
                }
            });
        });
    };
    return DBHelper;
}());
exports.DBHelper = DBHelper;
//# sourceMappingURL=DBHelper.js.map