"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 app_events_factory_1 = require("../factory/app-events.factory");
var const_util_1 = require("../utils/const.util");
var DatabaseController = (function () {
    function DatabaseController() {
    }
    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 (database, options) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2, database.init(options)];
            });
        });
    };
    DatabaseController.prototype.writeOne = function (domain, data, database, security, context, options, configs) {
        if (options === void 0) { options = { bypassDomainVerification: false }; }
        return __awaiter(this, void 0, void 0, function () {
            var returnFields, sanitizedDataWithCreateMetadata, sanitizedData, doc, cleanDoc;
            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(data);
                        sanitizedDataWithCreateMetadata = this.addCreateMetadata(data, security, context);
                        sanitizedData = this.sanitize4Db(sanitizedDataWithCreateMetadata);
                        return [4, database.writeOne(domain, sanitizedData, context, configs)];
                    case 3:
                        doc = _a.sent();
                        cleanDoc = this.sanitize4User(doc, returnFields, [], false, security);
                        this.publishChanges(domain, {
                            _id: doc === null || doc === void 0 ? void 0 : doc._id,
                            fullDocument: doc,
                            documentKey: doc === null || doc === void 0 ? void 0 : doc._id,
                            operationType: "create"
                        });
                        return [2, cleanDoc];
                }
            });
        });
    };
    DatabaseController.prototype.writeMany = function (domain, data, database, security, context, options, configs) {
        if (options === void 0) { options = { bypassDomainVerification: false }; }
        return __awaiter(this, void 0, void 0, function () {
            var freshData, returnFieldsMap, sanitizedData, docs;
            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:
                        freshData = data.map(function (value) { return _this.addCreateMetadata(value, security, context); });
                        returnFieldsMap = freshData.reduce(function (a, b) {
                            a[b._id] = b.return;
                            return a;
                        }, {});
                        sanitizedData = freshData.map(function (value) { return _this.sanitize4Db(value); });
                        return [4, database.writeMany(domain, sanitizedData, context, configs)];
                    case 3:
                        docs = _a.sent();
                        return [2, docs.map(function (x1) {
                                var cleanDoc = _this.sanitize4User(x1, returnFieldsMap[x1._id], [], false, security);
                                _this.publishChanges(domain, {
                                    _id: x1 === null || x1 === void 0 ? void 0 : x1._id,
                                    fullDocument: x1,
                                    documentKey: x1 === null || x1 === void 0 ? void 0 : x1._id,
                                    operationType: "create"
                                });
                                return cleanDoc;
                            })];
                }
            });
        });
    };
    DatabaseController.prototype.updateOne = function (domain, updateModel, database, security, context, options, configs) {
        if (options === void 0) { options = { bypassDomainVerification: false }; }
        return __awaiter(this, void 0, void 0, function () {
            var returnFields, updatedDoc, cleanDoc;
            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:
                        if (updateModel.upsert === true) {
                            if (!updateModel.update.hasOwnProperty('$set')) {
                                updateModel.update.$set = { id: security.generateUUID() };
                            }
                        }
                        returnFields = this.getReturnFields(updateModel);
                        updateModel = this.altUpdateModel(updateModel, context);
                        options.dbOptions = updateModel && updateModel.options ? updateModel.options : {};
                        return [4, database.updateOne(domain, updateModel, context, configs)];
                    case 3:
                        updatedDoc = _a.sent();
                        cleanDoc = this.sanitize4User(updatedDoc, returnFields, [], updateModel.cids, security);
                        this.publishChanges(domain, {
                            _id: updatedDoc === null || updatedDoc === void 0 ? void 0 : updatedDoc._id,
                            fullDocument: updatedDoc,
                            documentKey: updatedDoc === null || updatedDoc === void 0 ? void 0 : updatedDoc._id,
                            operationType: "update"
                        });
                        return [2, cleanDoc];
                }
            });
        });
    };
    DatabaseController.prototype.altUpdateModel = function (updateModel, context) {
        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);
        return updateModel;
    };
    DatabaseController.prototype.updateMany = function (domain, updateModel, database, security, context, options, configs) {
        if (options === void 0) { options = { bypassDomainVerification: false }; }
        return __awaiter(this, void 0, void 0, function () {
            var docs;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(updateModel.filter &&
                            typeof updateModel.filter === 'object' &&
                            Object.keys(updateModel.filter).length > 0)) return [3, 4];
                        if (!(options && options.bypassDomainVerification === false)) return [3, 2];
                        return [4, this.handleDomainValidation(domain)];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2:
                        if (updateModel.upsert === true) {
                            if (!updateModel.update.hasOwnProperty('$set')) {
                                updateModel.update.$set = {};
                            }
                            if (!updateModel.update.$set.hasOwnProperty('_id')) {
                                updateModel.update.$set._id = security.generateUUID();
                            }
                        }
                        updateModel = this.altUpdateModel(updateModel, context);
                        options.dbOptions = updateModel && updateModel.options ? updateModel.options : {};
                        return [4, database.updateMany(domain, updateModel, context, configs)];
                    case 3:
                        docs = _a.sent();
                        return [2, docs.map(function (_t1) {
                                var cleanDoc = _this.sanitize4User(_t1, updateModel.return, [], updateModel.cids, security);
                                _this.publishChanges(domain, {
                                    _id: _t1 === null || _t1 === void 0 ? void 0 : _t1._id,
                                    fullDocument: _t1,
                                    documentKey: _t1 === null || _t1 === void 0 ? void 0 : _t1._id,
                                    operationType: "update"
                                });
                                return cleanDoc;
                            })];
                    case 4: throw { message: 'you must supply filter object in update model' };
                }
            });
        });
    };
    DatabaseController.prototype.delete = function (domain, deleteModel, database, security, context, options, configs) {
        if (options === void 0) { options = { bypassDomainVerification: false }; }
        return __awaiter(this, void 0, void 0, function () {
            var result;
            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:
                        deleteModel.filter = this.sanitizeWithOperator4Db(deleteModel === null || deleteModel === void 0 ? void 0 : deleteModel.filter);
                        return [4, database.delete(domain, deleteModel, context, configs)];
                    case 3:
                        result = _a.sent();
                        return [2, result.map(function (t) {
                                var cleanDoc = _this.sanitize4User(t, deleteModel.return, [], false, security);
                                _this.publishChanges(domain, {
                                    _id: t === null || t === void 0 ? void 0 : t._id,
                                    fullDocument: t,
                                    documentKey: t === null || t === void 0 ? void 0 : t._id,
                                    operationType: "delete"
                                });
                                return cleanDoc;
                            })];
                }
            });
        });
    };
    DatabaseController.prototype.bulk = function (database, operations) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2, database.bulk(operations)];
            });
        });
    };
    DatabaseController.prototype.changes = function (domain, pipeline, database, security, 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, database.changes(domain, pipeline, function (doc) {
                            switch (doc.operationType) {
                                case 'create':
                                    listener({
                                        name: 'create',
                                        resumeToken: doc._id,
                                        snapshot: _this.sanitize4User(doc.fullDocument, [], [], false, security)
                                    });
                                    return;
                                case 'update':
                                    listener({
                                        name: 'update',
                                        resumeToken: doc._id,
                                        snapshot: _this.sanitize4User(doc.fullDocument, [], [], false, security)
                                    });
                                    return;
                                case 'delete':
                                    listener({
                                        name: 'delete',
                                        resumeToken: doc._id,
                                        snapshot: _this.sanitize4User(doc.fullDocument, [], [], false, security)
                                    });
                                    return;
                            }
                        }, options.resumeToken)];
                }
            });
        });
    };
    DatabaseController.prototype.query = function (domain, queryModel, database, security, context, options, configs) {
        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 && queryModel.id)) 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, database.findOne(domain, queryModel, context, configs)];
                    case 3:
                        result = _a.sent();
                        return [2, this.sanitize4User(result, returnFields, queryModel === null || queryModel === void 0 ? void 0 : queryModel.hashes, queryModel.cids, security)];
                    case 4:
                        queryModel = this.sanitizeWithOperator4Db(queryModel);
                        queryModel.filter = this.sanitizeWithOperator4Db(queryModel === null || queryModel === void 0 ? void 0 : queryModel.filter);
                        queryModel.return = returnFields4Db;
                        return [4, database.findMany(domain, queryModel, context, configs)];
                    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, queryModel.cids, security); })];
                        }
                        return [2, result];
                }
            });
        });
    };
    DatabaseController.prototype.addUpdateMetadata = function (data, context) {
        if (data && typeof data !== 'boolean') {
            if (data.$set) {
                data.$set.updatedAt = data.$set.updatedAt ? data.$set.updatedAt : new Date();
            }
            else if (data.$inc) {
                data.$set = {};
                data.$set.updatedAt = new Date();
            }
            return data;
        }
        return data;
    };
    DatabaseController.prototype.validDomain = function (domain) {
        return (domain !== '_User' && domain !== '_Token' && domain !== '_Policy');
    };
    DatabaseController.prototype.addCreateMetadata = function (data, security, context) {
        data.createdBy = context === null || context === void 0 ? void 0 : context.uid;
        data.createdAt = data && data.createdAt ? data.createdAt : new Date();
        data.updatedAt = data && data.updatedAt ? data.updatedAt : new Date();
        if (data._id) {
            return data;
        }
        data._id = data && data.id ? data.id : security.generateUUID();
        delete data.id;
        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) {
        data = this.sanitize4Db(data);
        if (data === null || data === undefined) {
            return null;
        }
        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('_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._created_by;
            delete data._created_by;
        }
        return data;
    };
    DatabaseController.prototype.sanitize4User = function (data, returnFields, hashes, onlyCids, security) {
        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;
        }
        if (onlyCids === true) {
            return returnedData;
        }
        var dataHash = 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;
        }
    };
    DatabaseController.prototype.publishChanges = function (domain, change) {
        app_events_factory_1.AppEventsFactory.getInstance().pub(const_util_1.ConstUtil.DB_CHANGES_EVENT.concat(domain), change);
    };
    return DatabaseController;
}());
exports.DatabaseController = DatabaseController;
