const _ = require('lodash');

let config = require('./common');

let env = (
    process.env[config.env_variable_prefix + 'ENVIRONMENT'] ||
    process.env.NODE_ENV ||
    'development'
);

config.version = require('../package.json').version;
config.env = env;

try {
    _.merge(config, require(`./${env}.json`));
}
catch(e) {}

// process.env.PREFIX_X__Y_Z > config.x.y_z
Object.keys(process.env).forEach(argKey => {
    let configKey = argKey;

    if (config.env_variable_prefix && configKey.indexOf(config.env_variable_prefix) === 0)
        configKey = configKey.substring(config.env_variable_prefix.length);

    configKey = configKey.replace(/__/g, '.').toLowerCase();

    if (_.get(config, configKey) !== undefined) {
        try {
            _.set(config, configKey, JSON.parse(process.env[argKey]));
        }
        catch(e) {
            _.set(config, configKey, process.env[argKey]);
        }
    }
});

if (!_.get(config, 'api.directory_admin') && _.get(config, 'api.directory'))
    config.api.directory_admin = config.api.directory + '/admin';

module.exports = config;