import fs from 'fs';
import Papa from 'papaparse'; // eslint-disable-line import/no-extraneous-dependencies


const writeToFile = (folderpath, obj) => {
	const files = fs.readdirSync(folderpath);

	const lang = {};
	Object.keys(obj).forEach(k => {
		const keys = k.split('.');
		if (!lang[keys[0]]) { lang[keys[0]] = {}; }
		lang[keys[0]][keys.slice(1).join('.')] = obj[k];
	});

	const set = (object, key, value) => {
		const o = object;
		const keys = key.split('.');
		if (keys.length > 1) {
			if (!o[keys[0]]) o[keys[0]] = {};
			return set(o[keys[0]], keys.slice(1).join('.'), value);
		}
		o[key] = value;
		return o;
	};

	Object.keys(lang).forEach(filename => {
		if (files.indexOf(filename) >= 0) { // if the filename exist as folder
			writeToFile(`${folderpath}/${filename}`, lang[filename]);
		} else {
			// const fileContent = JSON.parse(fs.readFileSync(`${folderpath}/${filename}.json`, 'utf8'));
			const fileContent = { [filename]: {} };
			Object.keys(lang[filename]).sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase())).forEach(key => {
				if (lang[filename][key] !== '') set(fileContent[filename], key, lang[filename][key], Object);
			});
			fs.writeFileSync(`${folderpath}/${filename}.json`, `${JSON.stringify(fileContent, null, 2)}\n`);
		}
	});
};


// Process parameters supplied to the script
const args = process.argv.slice(2);
const [filepath, destPath] = args;

if (!filepath || !destPath) {
	// console.log('Please provide the path to csv file and path to lang (relative path)');
	// console.log('Example: babel-node import-from-csv.js ./lang.csv ./lang');
} else {
	const csv = fs.readFileSync(filepath, 'utf8');
	const { data: [keys, ...entries] } = Papa.parse(csv, { skipEmptyLines: true });
	const locales = keys.slice(1);
	const lang = {};
	entries.forEach(entry => {
		locales.forEach((locale, idx) => {
			if (!lang[locale]) { lang[locale] = {}; }
			lang[locale][entry[0]] = entry[idx + 1];
		});
	});

	locales.forEach((locale) => {
		writeToFile(`${destPath}/${locale}`, lang[locale]);
	});
}
