// Скачивание переведённых фраз из танкера

const fs = require('fs');
const path = require('path');
const _ = require('lodash');
const request = require('request');

const gulp = require('gulp');
const gutil = require('gulp-util');

const LOCALES = ['ru', 'en', 'tr'];

const destination = path.join(__dirname, '../locales');

const requestOptions = {
    url: 'https://tanker-api.yandex-team.ru/projects/export/json/',
    qs: {
        'project-id': 'portal',
        status: 'unapproved',
        safe: 1,
        'no-comments': 1,
    },
};

const downloadedKeys = [];

gulp.task('locales', done => {
    request.get(requestOptions, (error, res, response) => {
        if (error) {
            gutil.log('Failed to download resources from Tanker');
            gutil.log(error);
            done();
        }

        try {
            response = JSON.parse(response);
        } catch (e) {
            gutil.log('Failed to parse Tanker output');
            gutil.log(e);
            gutil.log(response);
        }

        LOCALES.forEach(locale => {
            const result = {};
            let original = require(path.join(destination, `${locale}.json`));

            // разбиение по кейсетам не нужно,
            // поэтому избавляемся от него
            _.forEach(response[locale], (keyset, key) => {
                if (!downloadedKeys.length || downloadedKeys.includes(key)) {
                    result[key] = keyset;
                } else {
                    result[key] = original[key];
                }
            });

            fs.writeFileSync(
                path.join(destination, `${locale}.json`),
                JSON.stringify(result, null, 4)
            );

            gutil.log(`Updated '${locale}.json'`);
        });

        done();
    });
});
