import Papa from 'papaparse'; // eslint-disable-line import/no-extraneous-dependencies
import fs from 'fs';
import * as json from './lang/**/*.json'; // eslint-disable-line import/no-unresolved


const flattenObject = (ob) => {
	const toReturn = {};
	Object.keys(ob).forEach(k => {
		if (typeof ob[k] === 'object') {
			const flatObject = flattenObject(ob[k]);
			Object.keys(flatObject).forEach(x => {
				toReturn[`${k}.${x}`] = flatObject[x];
			});
		} else {
			toReturn[k] = ob[k];
		}
	});
	return toReturn;
};

const lang = {};
Object.keys(json).forEach(filepath => {
	const path = filepath.split('$').slice(0, -1);
	const locale = path[0];
	const keyPrefix = path.slice(1).join('.');
	if (!lang[locale]) { lang[locale] = {}; }
	if (keyPrefix) {
		lang[locale][keyPrefix] = { ...lang[locale][keyPrefix], ...json[filepath] };
	} else {
		lang[locale] = { ...lang[locale], ...json[filepath] };
	}
});


const locales = Object.keys(lang);
const forCSV = {};
Object.keys(lang).forEach(key => {
	const flatObject = flattenObject(lang[key]);
	Object.keys(flatObject).forEach(x => {
		if (!forCSV[x]) {
			forCSV[x] = {};
			locales.forEach(l => { forCSV[x][l] = ''; });
		}
		forCSV[x][key] = flatObject[x];
	});
});


const csv = Papa.unparse({
	fields: ['key', ...Object.keys(lang)],
	data: Object.entries(forCSV).map(entry => [entry[0], ...Object.values(entry[1])]),
});

fs.writeFileSync('language.csv', csv);
