"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = __importDefault(require("fs"));
const os_1 = require("os");
const path_1 = __importDefault(require("path"));
const logger_1 = __importDefault(require("./logger"));
const utils_1 = require("./utils");
const parseArgv_1 = __importDefault(require("./utils/parseArgv"));
const program = (0, parseArgv_1.default)([], ['config']);
function findConfig() {
    const DEFAULT_CONFIG = path_1.default.join(__dirname, '../../../../bitcore.config.json');
    let bitcoreConfigPath = program.config || process.env.BITCORE_CONFIG_PATH || DEFAULT_CONFIG;
    if (bitcoreConfigPath[0] === '~') {
        bitcoreConfigPath = bitcoreConfigPath.replace('~', (0, os_1.homedir)());
    }
    if (!fs_1.default.existsSync(bitcoreConfigPath)) {
        throw new Error(`No bitcore config exists at ${bitcoreConfigPath}`);
    }
    const bitcoreConfigStat = fs_1.default.statSync(bitcoreConfigPath);
    if (bitcoreConfigStat.isDirectory()) {
        if (!fs_1.default.existsSync(path_1.default.join(bitcoreConfigPath, 'bitcore.config.json'))) {
            throw new Error(`No bitcore config exists in directory ${bitcoreConfigPath}`);
        }
        bitcoreConfigPath = path_1.default.join(bitcoreConfigPath, 'bitcore.config.json');
    }
    logger_1.default.info('Using config at: ' + bitcoreConfigPath);
    let rawBitcoreConfig;
    try {
        rawBitcoreConfig = fs_1.default.readFileSync(bitcoreConfigPath).toString();
    }
    catch (error) {
        throw new Error(`Error in loading bitcore config\nFound file at ${bitcoreConfigPath}\n${error}`);
    }
    let bitcoreConfig;
    try {
        bitcoreConfig = JSON.parse(rawBitcoreConfig).bitcoreNode;
    }
    catch (error) {
        throw new Error(`Error in parsing bitcore config\nFound and loaded file at ${bitcoreConfigPath}\n${error}`);
    }
    return bitcoreConfig;
}
function setTrustedPeers(config) {
    for (const [chain, chainObj] of Object.entries(config)) {
        for (const network of Object.keys(chainObj)) {
            const env = process.env;
            const envString = `TRUSTED_${chain.toUpperCase()}_${network.toUpperCase()}_PEER`;
            if (env[envString]) {
                const peers = config.chains[chain][network].trustedPeers || [];
                peers.push({
                    host: env[envString],
                    port: env[`${envString}_PORT`]
                });
                config.chains[chain][network].trustedPeers = peers;
            }
        }
    }
    return config;
}
const Config = function () {
    let config = {
        maxPoolSize: 50,
        port: 3000,
        dbUrl: process.env.DB_URL || '',
        dbHost: process.env.DB_HOST || '127.0.0.1',
        dbName: process.env.DB_NAME || 'bitcore',
        dbPort: process.env.DB_PORT || '27017',
        dbUser: process.env.DB_USER || '',
        dbPass: process.env.DB_PASS || '',
        numWorkers: (0, os_1.cpus)().length,
        chains: {},
        aliasMapping: {
            chains: {},
            networks: {}
        },
        services: {
            api: {
                rateLimiter: {
                    disabled: false,
                    whitelist: ['::ffff:127.0.0.1', '::1']
                },
                wallets: {
                    allowCreationBeforeCompleteSync: false,
                    allowUnauthenticatedCalls: false
                }
            },
            event: {
                onlyWalletEvents: false
            },
            p2p: {},
            socket: {
                bwsKeys: []
            },
            storage: {}
        },
        externalProviders: {
            moralis: {
                apiKey: 'string'
            }
        }
    };
    config = (0, utils_1.merge)(config, findConfig());
    if (!Object.keys(config.chains).length) {
        Object.assign(config.chains, {
            BTC: {
                mainnet: {
                    chainSource: 'p2p',
                    trustedPeers: [{ host: '127.0.0.1', port: 8333 }],
                    rpc: {
                        host: '127.0.0.1',
                        port: 8332,
                        username: 'bitcoin',
                        password: 'bitcoin'
                    }
                }
            }
        });
    }
    if (config.modules) {
        throw new Error('The config modules has moved! You can remove the `modules` array from your config to use the defaults, or if you need to use custom modules then you can specify the paths in the specific chain-network config objects with `modulePath`');
    }
    config = setTrustedPeers(config);
    return config;
};
exports.default = Config();
//# sourceMappingURL=config.js.map