"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.DatabaseController = void 0;
var DatabaseController = (function () {
    function DatabaseController(database, security) {
        this.database = database;
        this.security = security;
    }
    DatabaseController.prototype.handleDomainValidation = function (domain) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                if (!this.validDomain(domain)) {
                    throw {
                        message: domain + " is not a valid domain name"
                    };
                }
                return [2, true];
            });
        });
    };
    DatabaseController.prototype.init = function (mandatory) {
        if (mandatory === void 0) { mandatory = false; }
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2, this.database.init()];
            });
        });
    };
    DatabaseController.prototype.addIndexes = function (domain, indexes) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                if (indexes && Array.isArray(indexes)) {
                    return [2, this.database.createIndexes(domain, indexes)];
                }
                else {
                    throw new Error('Must supply array of indexes to be added');
                }
                return [2];
            });
        });
    };
    DatabaseController.prototype.removeIndexes = function (domain) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2, this.database.dropIndexes(domain)];
            });
        });
    };
    DatabaseController.prototype.listIndexes = function (domain) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2, this.database.listIndexes(domain)];
            });
        });
    };
    DatabaseController.prototype.writeOne = function (domain, data, context, options) {
        if (options === void 0) { options = { bypassDomainVerification: false }; }
        return __awaiter(this, void 0, void 0, function () {
            var returnFields, sanitizedData, sanitizedDataWithCreateMetadata, _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        if (!(options && options.bypassDomainVerification === false)) return [3, 2];
                        return [4, this.handleDomainValidation(domain)];
                    case 1:
                        _b.sent();
                        _b.label = 2;
                    case 2:
                        returnFields = this.getReturnFields(data);
                        sanitizedData = this.sanitize4Db(data);
                        sanitizedDataWithCreateMetadata = this.addCreateMetadata(sanitizedData, context);
                        _a = sanitizedDataWithCreateMetadata;
                        return [4, this.database.writeOne(domain, sanitizedDataWithCreateMetadata, context, options)];
                    case 3:
                        _a._id = _b.sent();
                        return [2, this.sanitize4User(sanitizedDataWithCreateMetadata, returnFields, [])];
                }
            });
        });
    };
    DatabaseController.prototype.update = function (domain, updateModel, context, options) {
        if (options === void 0) { options = { bypassDomainVerification: false }; }
        return __awaiter(this, void 0, void 0, function () {
            var returnFields, updatedDoc;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(options && options.bypassDomainVerification === false)) return [3, 2];
                        return [4, this.handleDomainValidation(domain)];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2:
                        returnFields = this.getReturnFields(updateModel);
                        updateModel.update = this.sanitizeWithOperator4Db(updateModel === null || updateModel === void 0 ? void 0 : updateModel.update);
                        updateModel.filter = this.sanitizeWithOperator4Db(updateModel === null || updateModel === void 0 ? void 0 : updateModel.filter);
                        updateModel.update = this.addUpdateMetadata(updateModel === null || updateModel === void 0 ? void 0 : updateModel.update, context);
                        options.dbOptions = updateModel && updateModel.options ? updateModel.options : {};
                        return [4, this.database.update(domain, updateModel, context, options)];
                    case 3:
                        updatedDoc = _a.sent();
                        return [2, this.sanitize4User(updatedDoc, returnFields, [])];
                }
            });
        });
    };
    DatabaseController.prototype.delete = function (domain, deleteModel, context, options) {
        if (options === void 0) { options = { bypassDomainVerification: false }; }
        return __awaiter(this, void 0, void 0, function () {
            var result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(options && options.bypassDomainVerification === false)) return [3, 2];
                        return [4, this.handleDomainValidation(domain)];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2:
                        deleteModel.filter = this.sanitizeWithOperator4Db(deleteModel === null || deleteModel === void 0 ? void 0 : deleteModel.filter);
                        return [4, this.database.deleteOne(domain, deleteModel, context, options)];
                    case 3:
                        result = _a.sent();
                        return [2, this.sanitize4User(result, ['id'], [])];
                }
            });
        });
    };
    DatabaseController.prototype.transaction = function (operations) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2, this.database.transaction(operations)];
            });
        });
    };
    DatabaseController.prototype.aggregate = function (domain, pipelines, hashes, context, options) {
        if (options === void 0) { options = { bypassDomainVerification: false }; }
        return __awaiter(this, void 0, void 0, function () {
            var results;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(options && options.bypassDomainVerification === false)) return [3, 2];
                        return [4, this.handleDomainValidation(domain)];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2: return [4, this.database.aggregate(domain, pipelines, context, options)];
                    case 3:
                        results = _a.sent();
                        return [2, results.map(function (result) { return _this.sanitize4User(result, [], hashes); })];
                }
            });
        });
    };
    DatabaseController.prototype.changes = function (domain, pipeline, listener, options) {
        if (options === void 0) { options = { bypassDomainVerification: false, resumeToken: undefined }; }
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(options && options.bypassDomainVerification === false)) return [3, 2];
                        return [4, this.handleDomainValidation(domain)];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2: return [2, this.database.changes(domain, pipeline, function (doc) {
                            if (doc.operationType === 'insert') {
                                listener({
                                    name: 'create',
                                    resumeToken: doc._id,
                                    snapshot: _this.sanitize4User(doc.fullDocument, [], [])
                                });
                            }
                            else if (doc.operationType === 'replace') {
                                listener({
                                    name: 'create',
                                    resumeToken: doc._id,
                                    snapshot: _this.sanitize4User(doc.fullDocument, [], [])
                                });
                            }
                            else if (doc.operationType === 'update') {
                                listener({
                                    name: 'update',
                                    resumeToken: doc._id,
                                    snapshot: _this.sanitize4User(doc.fullDocument, [], [])
                                });
                            }
                            else if (doc.operationType === 'delete') {
                                listener({
                                    name: 'delete',
                                    resumeToken: doc._id,
                                    snapshot: _this.sanitize4User(doc.documentKey, [], [])
                                });
                            }
                        }, options.resumeToken)];
                }
            });
        });
    };
    DatabaseController.prototype.query = function (domain, queryModel, context, options) {
        if (options === void 0) { options = { bypassDomainVerification: false }; }
        return __awaiter(this, void 0, void 0, function () {
            var returnFields, returnFields4Db, result, result;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        returnFields = this.getReturnFields(queryModel);
                        returnFields4Db = this.getReturnFields4Db(queryModel);
                        if (!(options && options.bypassDomainVerification === false)) return [3, 2];
                        return [4, this.handleDomainValidation(domain)];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2:
                        if (!(queryModel && typeof queryModel !== 'boolean' && queryModel.id && typeof queryModel.id !== 'boolean')) return [3, 4];
                        queryModel = this.sanitizeWithOperator4Db(queryModel);
                        queryModel.filter = this.sanitizeWithOperator4Db(queryModel === null || queryModel === void 0 ? void 0 : queryModel.filter);
                        queryModel.return = returnFields4Db;
                        return [4, this.database.findOne(domain, queryModel, context, options)];
                    case 3:
                        result = _a.sent();
                        return [2, this.sanitize4User(result, returnFields, queryModel === null || queryModel === void 0 ? void 0 : queryModel.hashes)];
                    case 4:
                        queryModel = this.sanitizeWithOperator4Db(queryModel);
                        queryModel.filter = this.sanitizeWithOperator4Db(queryModel === null || queryModel === void 0 ? void 0 : queryModel.filter);
                        queryModel.return = returnFields4Db;
                        return [4, this.database.query(domain, queryModel, context, options)];
                    case 5:
                        result = _a.sent();
                        if (result && Array.isArray(result)) {
                            return [2, result.map(function (value) { return _this.sanitize4User(value, returnFields, queryModel === null || queryModel === void 0 ? void 0 : queryModel.hashes); })];
                        }
                        return [2, result];
                }
            });
        });
    };
    DatabaseController.prototype.writeMany = function (domain, data, context, options) {
        if (options === void 0) { options = { bypassDomainVerification: false }; }
        return __awaiter(this, void 0, void 0, function () {
            var returnFieldsMap, sanitizedData, freshData, insertedIds;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(options && options.bypassDomainVerification === false)) return [3, 2];
                        return [4, this.handleDomainValidation(domain)];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2:
                        returnFieldsMap = {};
                        data.forEach(function (value, index) {
                            returnFieldsMap[index] = value === null || value === void 0 ? void 0 : value.return;
                        });
                        sanitizedData = data.map(function (value) { return _this.sanitize4Db(value); });
                        freshData = sanitizedData.map(function (value) { return _this.addCreateMetadata(value, context); });
                        return [4, this.database.writeMany(domain, freshData, context, options)];
                    case 3:
                        insertedIds = _a.sent();
                        Object.keys(insertedIds).forEach(function (index) {
                            freshData[index]._id = insertedIds[index];
                            freshData[index] = _this.sanitize4User(freshData[index], returnFieldsMap[index], []);
                        });
                        return [2, freshData];
                }
            });
        });
    };
    DatabaseController.prototype.addUpdateMetadata = function (data, context) {
        if (data && typeof data !== 'boolean') {
            data.$currentDate = { _updated_at: true };
            return data;
        }
        return data;
    };
    DatabaseController.prototype.validDomain = function (domain) {
        return (domain !== '_User' && domain !== '_Token' && domain !== '_Policy');
    };
    DatabaseController.prototype.addCreateMetadata = function (data, context) {
        data._created_by = context === null || context === void 0 ? void 0 : context.uid;
        data._created_at = data && data._created_at ? data._created_at : new Date();
        data._updated_at = data && data._updated_at ? data._updated_at : new Date();
        if (data && (data._id === undefined || data._id === null) && typeof data !== 'boolean') {
            data._id = this.security.generateUUID();
        }
        return data;
    };
    DatabaseController.prototype.getReturnFields = function (data) {
        if (data && data.return && Array.isArray(data.return)) {
            var flag_1 = true;
            if (data.return.length > 0) {
                data.return.forEach(function (value) {
                    if (typeof value !== 'string') {
                        flag_1 = false;
                    }
                });
            }
            if (flag_1 === true) {
                return data.return;
            }
            else {
                return undefined;
            }
        }
        else {
            return undefined;
        }
    };
    DatabaseController.prototype.getReturnFields4Db = function (data) {
        var _this = this;
        if (data && data.return && Array.isArray(data.return)) {
            var flag_2 = true;
            if (data.return.length > 0) {
                data.return.forEach(function (value, index) {
                    var _a;
                    if (typeof value !== 'string') {
                        flag_2 = false;
                    }
                    data.return[index] = Object.keys(_this.sanitize4Db((_a = {}, _a[value] = 1, _a)))[0];
                });
            }
            if (flag_2 === true) {
                return data.return;
            }
            else {
                return undefined;
            }
        }
        else {
            return undefined;
        }
    };
    DatabaseController.prototype.sanitizeWithOperator4Db = function (data) {
        var _this = this;
        data = this.sanitize4Db(data);
        if (data === null || data === undefined) {
            return null;
        }
        Object.keys(data).forEach(function (key) {
            if (key.startsWith('$')) {
                data[key] = _this.sanitize4Db(data[key]);
            }
        });
        return data;
    };
    DatabaseController.prototype.sanitize4Db = function (data) {
        if (data === null || data === undefined) {
            return null;
        }
        if (data && data.hasOwnProperty('return')) {
            delete data.return;
        }
        if (data && data.hasOwnProperty('id')) {
            data._id = data.id;
            delete data.id;
        }
        if (data && data.hasOwnProperty('createdAt')) {
            data._created_at = data.createdAt;
            delete data.createdAt;
        }
        if (data && data.hasOwnProperty('updatedAt')) {
            data._updated_at = data.updatedAt;
            delete data.updatedAt;
        }
        if (data && data.hasOwnProperty('createdBy')) {
            data._created_by = data.createdBy;
            delete data.createdBy;
        }
        return data;
    };
    DatabaseController.prototype.sanitize4User = function (data, returnFields, hashes) {
        if (data === null || data === undefined) {
            return null;
        }
        if (data && data.hasOwnProperty('_id')) {
            data.id = data._id ? (typeof data._id === 'object' ? data._id : data._id.toString()) : '';
            delete data._id;
        }
        if (data && data.hasOwnProperty('_created_at')) {
            data.createdAt = data._created_at;
            delete data._created_at;
        }
        if (data && data.hasOwnProperty('_updated_at')) {
            data.updatedAt = data._updated_at;
            delete data._updated_at;
        }
        if (data && data.hasOwnProperty('_created_by')) {
            data.createdBy = data === null || data === void 0 ? void 0 : data._created_by;
            delete data._created_by;
        }
        if (data && data.hasOwnProperty('_hashed_password')) {
            if (!data.password) {
                data.password = data._hashed_password;
            }
            delete data._hashed_password;
        }
        if (data && typeof data.hasOwnProperty('_rperm')) {
            delete data._rperm;
        }
        if (data && typeof data.hasOwnProperty('_wperm')) {
            delete data._wperm;
        }
        if (data && typeof data.hasOwnProperty('_acl')) {
            delete data._acl;
        }
        if (!hashes) {
            hashes = [];
        }
        var returnedData = {};
        if (!returnFields && typeof returnFields !== 'boolean') {
            returnedData.id = data.id;
        }
        else if (returnFields && Array.isArray(returnFields) && returnFields.length === 0) {
            returnedData = data;
        }
        else {
            returnFields.forEach(function (value) {
                returnedData[value] = data[value];
            });
            returnedData.id = data.id;
            returnedData.createdAt = data.createdAt;
            returnedData.updatedAt = data.updatedAt;
        }
        if (returnedData === null || returnedData === undefined) {
            return null;
        }
        var dataHash = this.security.sha256OfObject(returnedData);
        var exists = hashes.filter(function (h) { return h === dataHash; });
        if (exists.length === 0) {
            return returnedData;
        }
        else if (exists.length === 1) {
            return dataHash;
        }
        else {
            return returnedData;
        }
    };
    return DatabaseController;
}());
exports.DatabaseController = DatabaseController;
