const path = require('path');
const cli = require('../cli-util');

const REQUIRED_FIELDS = [
    'buffer_directory',
    'build_registry',
    'app_repo'
];

const app = cli.getArg('--app');
const version = cli.getArg('-v') || cli.getArg('--version');

const config = {
    REQUIRED_FIELDS,
    buffer_directory: '.build'
};

let buildConfig = cli.read([
    cli.getArg('--config'),
    path.join(process.cwd(), 'build.config.json'),
    path.join(process.cwd(), app || '', 'build.config.json')
], 'json');

if (app && buildConfig && buildConfig.apps) {
    buildConfig = buildConfig.apps[app];
}

Object.assign(config, buildConfig || {});

let argConfig = {
    app,
    version,
    version_tag: [ app, version ].filter(Boolean).join('-'),
    buffer_directory: cli.getArg('-b') || cli.getArg('--buffer-directory'),
    build_registry: cli.getArg('--build-registry'),
    app_repo: cli.getArg('--app-repo'),
    npm_registry: cli.getArg('--npm-registry'),
    build_command: cli.getArg('--build-command'),
    destination: cli.getArg('--destination')
};

Object.keys(argConfig).forEach(key => {
    if (argConfig[key]) config[key] = argConfig[key];
});

// замена плейсхолдеров ${var} в команде значениями из конфига
config.apply = cmd => {
    if (typeof cmd === 'string') {
        return cli.template(cmd, config);
    }

    if (Array.isArray(cmd)) {
        return cmd.map(config.apply);
    }

    return cmd;
};

module.exports = config;