"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initialize = void 0;
const bfast_option_1 = require("./bfast-option");
const webservices_1 = require("./webservices");
const auth_1 = require("./factories/auth");
const s3_storage_1 = require("./factories/s3-storage");
const ipfs_storage_1 = require("./factories/ipfs-storage");
const database_1 = require("./controllers/database");
const mongo_database_1 = require("./factories/mongo-database");
function getAuthFactory(options) {
    return (options && options.adapters && options.adapters.auth)
        ? options.adapters.auth(options)
        : new auth_1.AuthFactory();
}
function getDatabaseFactory(options) {
    return (options && options.adapters && options.adapters.database)
        ? options.adapters.database(options)
        : new mongo_database_1.MongoDatabaseFactory();
}
function getFilesFactory(options) {
    if (!options.adapters)
        options.adapters = {};
    return (options &&
        options.adapters &&
        options.adapters.s3Storage &&
        typeof options.adapters.s3Storage === "object")
        ? new s3_storage_1.S3StorageFactory()
        : new ipfs_storage_1.IpfsStorageFactory();
}
async function setUpDatabase(options) {
    const databaseFactory = getDatabaseFactory(options);
    return (0, database_1.initDataStore)(databaseFactory, options);
}
function initialize(options) {
    let reason;
    if ((0, bfast_option_1.isBFastOptions)(options, r => reason = r)) {
        setUpDatabase(options).catch(_ => {
            console.error(_);
            process.exit(-1);
        });
        const fileF = getFilesFactory(options);
        fileF.init(options).catch(console.log);
        const authFactory = getAuthFactory(options);
        const databaseFactory = getDatabaseFactory(options);
        return new webservices_1.WebServices(authFactory, fileF, databaseFactory, options);
    }
    else
        throw { message: reason };
}
exports.initialize = initialize;
