import fs from 'fs';

const languages = ["de", "en"];
const defaultLocale = "de";

function testKeys(defaultTranslation: any, translation: any,messages: string[]){
	if (defaultTranslation === undefined || translation == undefined){
		return;
	}
	// check if keys in default locale file are all translated in other locale
	Object.keys(defaultTranslation).forEach((key) => {
		if (Object.keys(translation).indexOf(key) === -1) {
			messages.push(`key missing: '${key}'`);
		}
	});
	// check if there is unused key in other locale
	Object.keys(translation).forEach((key) => {
		if (Object.keys(defaultTranslation).indexOf(key) === -1) {
			messages.push(`unexpected key: '${key}'`);
		}
	});
	// recursive
	Object.entries(translation).forEach(([key,value]) => {
		if (typeof value == "object") {
			testKeys(defaultTranslation[key], translation[key], messages)
		}
	});
}

describe('Translations should', () => {
	let translations: {lang:string, translation: any}[] = [];
	beforeAll(async ()=>{
		for (let l of languages){
			let f;
			try {
				f = fs.readFileSync('./public/locales/'+l+'/translation.json','utf-8');
			} catch (e){
				console.log(e)
				throw new Error(`Could not find file for locale '${l}'.`)
			}
			try {
				let t = JSON.parse(<string>f)
				translations.push({lang:l, translation: t})
			} catch (e){
				throw new Error(`locale '${l}' has no valid json content.`)
			}
		}
	})

	test('All languages Should exist', async () => {
		expect(translations.length).toBe(languages.length)
	});
	test.each(languages)("Test all Locales have the same keys",async (a:string) => {
		if (a === defaultLocale){
			return;
		}
		let messages: string[] = [];
		let defaultTranslation = translations.find(x=>x.lang === defaultLocale)?.translation;
		let translation = translations.find(x=>x.lang === a)?.translation;
		testKeys(defaultTranslation, translation, messages)
		if (messages.length >0){
			throw new Error(`Problems in Locale ${a}:\n ${messages.join('\n - ')}`)
		}
	});
});