var lang = {} // MOVED TO EN / DE .JSON FILES !!!

var newLang = {}
var supportedLang = ['de', 'en', 'es', 'fr', 'it', 'pl', 'ru', 'cz', 'sw', 'nl'];

function getLangJSON() {
	return new Promise((resolve, reject) => {
		initLang();
		newLang = {}

		let lang = app.lang;
		let langJSONArr = [
			"dashboard", "debug-api", "devices-blinds", "devices-lights", "devices-plugs",
			"devices-sensors", "devices-switches", "devices-thermostats", "global", "group-lamps", "group-scene", 
			"group-sensors", "group-switches", "group-time", "index", "login", "settings-gateway", "settings-wifi",
			"settings-view", "sidemenue-help", "device-integration", "daily-schedules", "group-automations", "themes"
		];
		let dir = 'language';

		let promises = [];

		langJSONArr.forEach(fileName => {
			let path = `${dir}\/${lang}\/${fileName}-${lang}.json`;

			promises.push(
				fetchLangJSON(path)
					.then(dat => {
						//console.log(dat)
						newLang = Object.assign (newLang, dat);
					})
					.catch(err => {
						//console.log(err)
						path = path = `\/${dir}\/en\/${fileName}-en.json`;
						return fetchLangJSON(path);
					})
					.then(dat => {
						//console.log(dat)
						newLang = Object.assign(newLang, dat);
						promises.push(Promise.resolve())
					})
					.catch(err => console.log(err))
			);
		});

		Promise.all(promises)
			.then(() => resolve())
	})
}

function fetchLangJSON(path) {
	return new Promise((resolve, reject) => {
		fetch (path)
			.then(res => res.json())
	  		.then(dat => resolve(dat))
			.catch(err => reject(err));
	});
}

function getSysLang() {
	let sysLang = navigator.language;
	sysLang = sysLang.split('-')[0];

	if (!sysLang || supportedLang.indexOf(sysLang) === -1)
		sysLang = 'en';

	return sysLang;
}

function initLang() {
	var lan = localStorage.getItem('app.lang') || getSysLang();
	app.lang = lan;
}

function loadLanguage() {
	if (Object.keys(newLang).length === 0) {
		getLangJSON()
			.then(translateAll);
	} else {
		translateAll()
	}

}

function translateAll() {
	var nodes = document.querySelectorAll('[data-translateid]');

	Array.prototype.forEach.call(nodes, function(el) {
		var id = el.dataset["translateid"];
		if (!id)
			return;

		if (el.nodeName === 'INPUT' && el.placeholder) {
			el.placeholder = translate(id);
		} else if (el.nodeName === 'OPTION' && el.innerText.trim().length === 0) {
			el.value = translate(id);
		} else if (el.nodeName === 'OPTGROUP') {
			el.label = translate(id);
		} else if (el.nodeName === 'INPUT' && el.type === "submit") {
			el.value = translate(id);
		} else {
			el.innerHTML = translate(id);
		}
	});
}

function translate(id, rl) {
	if (!rl) {
        initLang();
        rl = app.lang || 'en';
	}

    if (id && newLang[id]) {
		return newLang[id];
	} else if (rl && rl in lang && id in lang[rl]) {
		return lang[rl][id];
	}
	
    var err = "TODO " + id + ", " + app.lang;

	try {
		//console.log(err);
	} catch(e) {
		return "";
	}
}

/**
 * Only translates errorLine of inputFields
 *
 * @memberOf module:global/functions
 *
 * @returns {void}
 */
function loadErrorsLanguage (){
	$('.text-danger > span[data-translateid]').each(function(){
		var id = $(this).attr('data-translateid');
		let txt = translate(id);
		$('[data-translateid=' + id + ']').text(txt);
	});
}


/* function initLanguage() {
	if (app._langInit)
		return;

	var lan = localStorage.getItem('app.lang') || navigator.language;

	var supported = Object.keys(lang); // "en", "de", ...

	if (supported.indexOf(lan) === -1) {
		// try to find similar language by prefix matching: de-AT, de-CH, en-US, en-GB, ...
		var x = supported.find(function(l) {
			return lan.indexOf(l) === 0;
		});

		lan = x || 'en'; // use match or fallback to english
	}

	setLang(lan);

	app._langInit = true;
} */

/**
 * Translate all elements in GUI
 *
 * @memberOf module:global/functions
 *
 * @returns {void}
 */

/* function loadLanguage() {

	initLanguage();

	var nodes = document.querySelectorAll('[data-translateid]');

	Array.prototype.forEach.call(nodes, function(el) {

		var id = el.dataset["translateid"];
		if (!id)
			return;

		// $('#select_scene').selectpicker('refresh'); TODO not the right place ...

		if (el.nodeName === 'INPUT' && el.placeholder) {
			el.placeholder = translate(id);
		} else if (el.nodeName === 'OPTION' && el.innerText.trim().length === 0) {
			el.value = translate(id);
		} else {
			el.innerHTML = translate(id);
		}
	});
} */

/**
 * Returns a translated string
 *
 * @memberOf module:global/functions
 *
 * @param {string} id the translation id
 * @param {string} rl [rl=app.lang] the requested language
 *
 * @returns {string} if(rl && rl in lang && id in lang[rl]) returns lang[rl][id], otherwise returns an error string
 */
/* function translate(id, rl) {
    if (!rl) {
        initLanguage();
        rl = app.lang || 'en';
    }

    if (rl && rl in lang && id in lang[rl])
        return lang[rl][id];

    var err = "TODO translation for id=" + id + ", lang=" + rl + " missing";
    console.log(err);
    return err;
 } */

/**
 * Set the language of current user
 *
 * @memberOf module:global/functions
 *
 * @param {string} lan language of current user
 *
 * @returns {void}
 */
/* function setLang(lan) {
	app.lang = lan;
}
 */
