
var lang = new Lang();
//lang.dynamic('th', '../../langpack/th.json');
//lang.dynamic('en', '../../langpack/en.json');

//List of _locals folders
function getLocales(callback) {
	if (typeof chrome=='undefined' ){
		return;
	}
	if (typeof chrome.runtime=='undefined' ){
		return;
	}
	if (typeof chrome.runtime.getPackageDirectoryEntry=='undefined' ){
		return;
	}
  chrome.runtime.getPackageDirectoryEntry(function(root) {
	root.getDirectory("langpack", {create: false}, function(localesdir) {
	  var reader = localesdir.createReader();
	  // Assumes that there are fewer than 100 locales; otherwise see DirectoryReader docs
	  reader.readEntries(function(results) {
		callback(results.map(function(de){return de.name;}).sort());
	  });
	});
  });
}
function loadInitLang(){
	getLocales(async function(data){
		//console.log("getLocales");
		//console.log(data);
		if(data){
			
			try{
				let select = document.getElementsByClassName("data_lang_oa_tl");
				for (let i = 0; i < select.length; i++) {
					select[i].options.length=0;
				}
				//document.getElementsByClassName("data_lang_oa_tl").options.length=0;
			}catch(e){console.log(e);}	//clear all items}
			for(let i=0;i<data.length;i++){
				try{
					let lang_name = data[i].split(".");
					let langname = lang_name[0].trim();
					let locale = 'en';	//default;
					if(langname){
						locale = langname.split("-")[0];
						try{
							let select = document.getElementsByClassName("data_lang_oa_tl");
							for (let i = 0; i < select.length; i++) {
								let opt = document.createElement('option');
								opt.value = locale.trim();
								opt.innerHTML = (langname.split("-")[1]).trim();
								select[i].appendChild(opt);
							}
						}catch(e){console.log(e);}
					}
					await lang.dynamic(locale, '../../langpack/'+langname+'.json');
				}catch(e){console.log(e);}
			}
			
			await lang.init({
				defaultLang: 'en'
			});
			setTimeout(function(){
				const data_lang = document.getElementsByClassName("data_lang_oa_tl");
				for(let j =0;j<data_lang.length;j++){
					let data_lang_opt = data_lang[j];
					for(let i =0;i<data_lang_opt.length;i++){
						let opt = data_lang_opt.options[i];
						console.log(opt.value.toLowerCase().trim());
						if(opt.value.toLowerCase().trim()==lang.currentLang){
							data_lang_opt.selectedIndex = i;
							break;
						}
					}
					
					
					data_lang_opt.addEventListener("change", function(e) {
						let opt = data_lang_opt.options[data_lang_opt.selectedIndex];
						console.log(opt.value);
						window.lang.change(opt.value);
						let select = document.getElementsByClassName("data_lang_oa_tl");
						for (let k = 0; k < select.length; k++) {
							if(select[k].id!=data_lang_opt.id){
								select[k].selectedIndex = data_lang_opt.selectedIndex;
							}
						}
					});
					 
					
				}
			},100);
		}
	});
}
