"use strict";
/**
 * Mongo Factory functions
 *
 *  Copyright (C) 2010-2020 R-T Specialty, LLC.
 *
 *  This file is part of the Liza Data Collection Framework.
 *
 *  liza is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * These definitions are for a very old mongodb library, which will be
 * once we get around to updating node.  Quite a failure on the maintenance
 * front.
 *
 * instantiate objects for MongoDb
 */
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.getClient = exports.getSeqCollection = exports.getQuotesCollection = exports.MongoFactory = void 0;
var mongodb_1 = require("mongodb");
var MongoServerDao_1 = require("../../server/db/MongoServerDao");
/**
 * Used to create Mongo services
 *
 * @param env     - env name
 * @param ts_ctor - unix timestamp constructor
 *
 * @return a Mongo Factory
 */
exports.MongoFactory = function (env) { return function (ts_ctor) {
    return {
        createDatabase: function () { return __awaiter(void 0, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, getClient(process.env).then(function (client) { return client.db('program'); })];
            });
        }); },
        createDao: function (db) { return __awaiter(void 0, void 0, void 0, function () {
            var _a, quote_collection, sequence_collection, _b, _c, _d, _e, _f;
            return __generator(this, function (_g) {
                switch (_g.label) {
                    case 0:
                        _c = (_b = Promise).all;
                        _d = getQuotesCollection;
                        return [4 /*yield*/, db];
                    case 1:
                        _e = [
                            _d.apply(void 0, [_g.sent()])
                        ];
                        _f = getSeqCollection;
                        return [4 /*yield*/, db];
                    case 2: return [4 /*yield*/, _c.apply(_b, [_e.concat([
                                _f.apply(void 0, [_g.sent()])
                            ])])];
                    case 3:
                        _a = _g.sent(), quote_collection = _a[0], sequence_collection = _a[1];
                        return [2 /*return*/, new MongoServerDao_1.MongoServerDao(quote_collection, sequence_collection, env, ts_ctor)];
                }
            });
        }); },
    };
}; };
/**
 * Attempts to connect to the database and retrieve the quotes collection
 *
 * @param db - the mongo database
 *
 * @return the collection
 */
function getQuotesCollection(db) {
    return new Promise(function (resolve, reject) {
        db.collection('quotes', {}, function (err, coll) {
            if (err) {
                reject(err);
            }
            coll
                .createIndex({ id: 1 }, { unique: true })
                .then(function () { return coll.createIndex({ published: 1 }); })
                .then(function () { return coll.createIndex({ deltaError: 1 }); })
                .then(function () {
                return coll.createIndex([
                    ['published', 1],
                    ['deltaError', 1],
                ]);
            })
                .then(function () { return resolve(coll); });
        });
    });
}
exports.getQuotesCollection = getQuotesCollection;
/**
 * Attempts to connect to the database and retrieve the quotes collection
 *
 * @param db - the mongo database
 *
 * @return the collection
 */
function getSeqCollection(db) {
    return new Promise(function (resolve, reject) {
        db.collection('seq', {}, function (err, coll) {
            if (err) {
                reject(err);
            }
            resolve(coll);
        });
    });
}
exports.getSeqCollection = getSeqCollection;
/**
 * Create a mongodb client from the environment
 *
 * @param env - the environment variables
 *
 * @return the mongo client
 */
function getClient(env) {
    var host = env.MONGODB_HOST || '127.0.0.1', port = env.MONGODB_PORT || 27017, replset = env.LIZA_MONGODB_REPLSET, ha = +(env.LIZA_MONGODB_HA || 0) === 1, host_a = env.LIZA_MONGODB_HOST_A, port_a = +(env.LIZA_MONGODB_PORT_A || 0), host_b = env.LIZA_MONGODB_HOST_B, port_b = +(env.LIZA_MONGODB_PORT_B || 0);
    var connection_string = 'mongodb://' +
        (ha
            ? host_a + ':' + port_a + ',' + host_b + ':' + port_b
            : host + ':' + port);
    var options = ha
        ? { useUnifiedTopology: true, replicaSet: replset || 'rs0' }
        : { useUnifiedTopology: true };
    return mongodb_1.MongoClient.connect(connection_string, options);
}
exports.getClient = getClient;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiTW9u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