const fs = require('fs');
const querystring = require('querystring');
const fetch = require('node-fetch');
const cli = require('../cli-util');
const config = require('./config');
const audit = require('./audit');

if (cli.hasArg('--help')) {
    return cli.help(config.app);
}

let url = 'https://tanker-api.yandex-team.ru/projects/export/json/';
let projectId;

if (config.fetch_options) {
    url += '?' + querystring.stringify(config.fetch_options);
    projectId = config.fetch_options['project-id'];
}

if (!projectId) {
    console.log(cli.error('The Tanker project ID is not specified.'));
    console.log('It should be defined under \'fetch_options[project-id]\' in a config file.');
    return;
}

fetch(url)
    .then(res => res.json())
    .then(data => {
        console.log(`✔ fetch tanker:${projectId}\n`);

        Object.keys(data).forEach(locale => {
            if (Array.isArray(config.locales) && config.locales.indexOf(locale) === -1) {
                return;
            }

            console.log(`✔ pick ${locale}@tanker:${projectId}`);
            audit(data[locale]);

            if (config.extra_resources && Array.isArray(config.extra_resources[locale])) {
                config.extra_resources[locale].forEach(resourcePath => {
                    try {
                        const resourceContent = cli.read(resourcePath, 'json');

                        Object.assign(data[locale], resourceContent);
                        console.log(`✔ fetch and merge '${resourcePath}'`);
                        audit(resourceContent);
                    }
                    catch(e) {
                        console.log(`✘ fetch and merge '${resourcePath}'`);
                    }
                });
            }

            const outputPath = (config.output ? config.output[locale] : null) || `${locale}.json`;

            fs.writeFileSync(outputPath, JSON.stringify(data[locale], null, 4));

            console.log(cli.bold(`✔ ${outputPath}\n`));
        });
    })
    .catch(error => {
        console.log(`\n✘ fetch tanker:${projectId}\n`);
        console.log(error);
    });
