"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.DatabaseFactory = void 0;
var mongodb_1 = require("mongodb");
var config;
var DatabaseFactory = (function () {
    function DatabaseFactory(configAdapter) {
        config = configAdapter;
    }
    DatabaseFactory.prototype.writeMany = function (domain, data, context, options) {
        return __awaiter(this, void 0, void 0, function () {
            var conn, response;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.connection()];
                    case 1:
                        conn = _a.sent();
                        return [4, conn.db()
                                .collection(domain)
                                .insertMany(data, {
                                session: options && options.transaction ? options.transaction : undefined
                            })];
                    case 2:
                        response = _a.sent();
                        conn.close().catch(console.warn);
                        return [2, response.insertedIds];
                }
            });
        });
    };
    DatabaseFactory.prototype.writeOne = function (domain, data, context, options) {
        return __awaiter(this, void 0, void 0, function () {
            var conn, response;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.connection()];
                    case 1:
                        conn = _a.sent();
                        return [4, conn.db().collection(domain)
                                .insertOne(data, {
                                session: options && options.transaction ? options.transaction : undefined
                            })];
                    case 2:
                        response = _a.sent();
                        return [2, response.insertedId];
                }
            });
        });
    };
    DatabaseFactory.prototype.connection = function () {
        return __awaiter(this, void 0, void 0, function () {
            var mongoUri;
            return __generator(this, function (_a) {
                mongoUri = config.mongoDbUri;
                return [2, new mongodb_1.MongoClient(mongoUri).connect()];
            });
        });
    };
    DatabaseFactory.prototype.init = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4, this.dropIndexes('_User')];
                    case 1:
                        _a.sent();
                        return [3, 3];
                    case 2:
                        _1 = _a.sent();
                        return [3, 3];
                    case 3: return [4, this.createIndexes('_User', [
                            {
                                field: 'email',
                                unique: true,
                                collation: {
                                    locale: 'en',
                                    strength: 2
                                }
                            },
                            {
                                field: 'username',
                                unique: true,
                                collation: {
                                    locale: 'en',
                                    strength: 2
                                }
                            }
                        ])];
                    case 4: return [2, _a.sent()];
                }
            });
        });
    };
    DatabaseFactory.prototype.createIndexes = function (domain, indexes) {
        return __awaiter(this, void 0, void 0, function () {
            var conn, _i, indexes_1, value, indexOptions;
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        if (!(indexes && Array.isArray(indexes))) return [3, 7];
                        return [4, this.connection()];
                    case 1:
                        conn = _b.sent();
                        _i = 0, indexes_1 = indexes;
                        _b.label = 2;
                    case 2:
                        if (!(_i < indexes_1.length)) return [3, 5];
                        value = indexes_1[_i];
                        indexOptions = {};
                        Object.assign(indexOptions, value);
                        delete indexOptions.field;
                        return [4, conn.db().collection(domain).createIndex((_a = {}, _a[value.field] = 1, _a), indexOptions)];
                    case 3:
                        _b.sent();
                        _b.label = 4;
                    case 4:
                        _i++;
                        return [3, 2];
                    case 5: return [4, conn.close()];
                    case 6:
                        _b.sent();
                        return [2, 'Indexes added'];
                    case 7: throw new Error('Must supply array of indexes to be added');
                }
            });
        });
    };
    DatabaseFactory.prototype.dropIndexes = function (domain) {
        return __awaiter(this, void 0, void 0, function () {
            var conn;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.connection()];
                    case 1:
                        conn = _a.sent();
                        return [4, conn.db().collection(domain).dropIndexes()];
                    case 2:
                        _a.sent();
                        return [4, conn.close()];
                    case 3:
                        _a.sent();
                        return [2, true];
                }
            });
        });
    };
    DatabaseFactory.prototype.listIndexes = function (domain) {
        return __awaiter(this, void 0, void 0, function () {
            var conn, indexes;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.connection()];
                    case 1:
                        conn = _a.sent();
                        return [4, conn.db().collection(domain).listIndexes().toArray()];
                    case 2:
                        indexes = _a.sent();
                        return [4, conn.close()];
                    case 3:
                        _a.sent();
                        return [2, indexes];
                }
            });
        });
    };
    DatabaseFactory.prototype.findOne = function (domain, queryModel, context, options) {
        return __awaiter(this, void 0, void 0, function () {
            var conn, fieldsToReturn, result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.connection()];
                    case 1:
                        conn = _a.sent();
                        fieldsToReturn = {
                            '_created_at': 1,
                            '_updated_at': 1,
                        };
                        if ((queryModel === null || queryModel === void 0 ? void 0 : queryModel.return) && Array.isArray(queryModel === null || queryModel === void 0 ? void 0 : queryModel.return) && queryModel.return.length > 0) {
                            queryModel.return.forEach(function (x) {
                                fieldsToReturn[x] = 1;
                            });
                        }
                        return [4, conn.db()
                                .collection(domain)
                                .findOne({ _id: queryModel._id }, {
                                session: options && options.transaction ? options.transaction : undefined,
                            })];
                    case 2:
                        result = _a.sent();
                        return [4, conn.close()];
                    case 3:
                        _a.sent();
                        return [2, result];
                }
            });
        });
    };
    DatabaseFactory.prototype.query = function (domain, queryModel, context, options) {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            var conn, query, fieldsToReturn_1, result;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4, this.connection()];
                    case 1:
                        conn = _b.sent();
                        query = conn.db().collection(domain).find(queryModel.filter, {
                            session: options && options.transaction ? options.transaction : undefined
                        });
                        if (queryModel.skip) {
                            query.skip(queryModel.skip);
                        }
                        else {
                            query.skip(0);
                        }
                        if (queryModel.size) {
                            if (queryModel.size !== -1) {
                                query.limit(queryModel.size);
                            }
                        }
                        else {
                            if (!queryModel.count) {
                                query.limit(50);
                            }
                        }
                        if (queryModel.orderBy && Array.isArray(queryModel.orderBy) && ((_a = queryModel.orderBy) === null || _a === void 0 ? void 0 : _a.length) > 0) {
                            queryModel.orderBy.forEach(function (value) {
                                query.sort(value);
                            });
                        }
                        if (queryModel.return && Array.isArray(queryModel.return) && queryModel.return.length > 0) {
                            fieldsToReturn_1 = {
                                '_created_at': 1,
                                '_updated_at': 1,
                            };
                            queryModel.return.forEach(function (x) {
                                fieldsToReturn_1[x] = 1;
                            });
                        }
                        if (!((queryModel === null || queryModel === void 0 ? void 0 : queryModel.count) === true)) return [3, 3];
                        return [4, query.count()];
                    case 2:
                        result = _b.sent();
                        return [3, 5];
                    case 3: return [4, query.toArray()];
                    case 4:
                        result = _b.sent();
                        _b.label = 5;
                    case 5: return [4, conn.close()];
                    case 6:
                        _b.sent();
                        return [2, result];
                }
            });
        });
    };
    DatabaseFactory.prototype.update = function (domain, updateModel, context, options) {
        return __awaiter(this, void 0, void 0, function () {
            var conn, updateOptions, response;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.connection()];
                    case 1:
                        conn = _a.sent();
                        updateOptions = {
                            upsert: typeof updateModel.upsert === 'boolean' ? updateModel.upsert : false,
                            returnOriginal: false,
                            returnDocument: 'after',
                            session: options && options.transaction ? options.transaction : undefined
                        };
                        updateOptions = Object.assign(updateOptions, options && options.dbOptions ? options.dbOptions : {});
                        return [4, conn.db().collection(domain)
                                .findOneAndUpdate(updateModel.filter, updateModel.update, updateOptions)];
                    case 2:
                        response = _a.sent();
                        return [4, conn.close()];
                    case 3:
                        _a.sent();
                        if (response.ok === 1) {
                            return [2, response.value];
                        }
                        else {
                            throw "Failt to updae";
                        }
                        return [2];
                }
            });
        });
    };
    DatabaseFactory.prototype.deleteOne = function (domain, deleteModel, context, options) {
        return __awaiter(this, void 0, void 0, function () {
            var conn, response;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.connection()];
                    case 1:
                        conn = _a.sent();
                        return [4, conn.db()
                                .collection(domain)
                                .findOneAndDelete(deleteModel.filter, {
                                session: options && options.transaction ? options.transaction : undefined
                            })];
                    case 2:
                        response = _a.sent();
                        return [4, conn.close()];
                    case 3:
                        _a.sent();
                        return [2, response.value];
                }
            });
        });
    };
    DatabaseFactory.prototype.transaction = function (operations) {
        return __awaiter(this, void 0, void 0, function () {
            var conn, session;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.connection()];
                    case 1:
                        conn = _a.sent();
                        session = conn.startSession();
                        _a.label = 2;
                    case 2:
                        _a.trys.push([2, , 4, 6]);
                        return [4, session.withTransaction(function (_) { return __awaiter(_this, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    switch (_a.label) {
                                        case 0: return [4, operations(session)];
                                        case 1: return [2, _a.sent()];
                                    }
                                });
                            }); }, {
                                writeConcern: {
                                    w: 'majority'
                                }
                            })];
                    case 3:
                        _a.sent();
                        return [3, 6];
                    case 4: return [4, session.endSession()];
                    case 5:
                        _a.sent();
                        return [7];
                    case 6: return [4, conn.close()];
                    case 7:
                        _a.sent();
                        return [2];
                }
            });
        });
    };
    DatabaseFactory.prototype.aggregate = function (domain, pipelines, context, options) {
        return __awaiter(this, void 0, void 0, function () {
            var conn, aggOps, result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.connection()];
                    case 1:
                        conn = _a.sent();
                        aggOps = {
                            allowDiskUse: true,
                            session: options && options.transaction ? options.transaction : undefined
                        };
                        return [4, conn.db().collection(domain).aggregate(pipelines, aggOps).toArray()];
                    case 2:
                        result = _a.sent();
                        return [4, conn.close()];
                    case 3:
                        _a.sent();
                        return [2, result];
                }
            });
        });
    };
    DatabaseFactory.prototype.changes = function (domain, pipeline, listener, resumeToken) {
        if (resumeToken === void 0) { resumeToken = undefined; }
        return __awaiter(this, void 0, void 0, function () {
            var conn, options;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.connection()];
                    case 1:
                        conn = _a.sent();
                        options = { fullDocument: 'updateLookup' };
                        if (resumeToken && resumeToken.toString() !== 'undefined' && resumeToken.toString() !== 'null') {
                            options.startAfter = resumeToken;
                        }
                        return [2, conn.db().collection(domain).watch(pipeline, options).on('change', function (doc) {
                                listener(doc);
                            })];
                }
            });
        });
    };
    return DatabaseFactory;
}());
exports.DatabaseFactory = DatabaseFactory;
