var yaml = require('js-yaml');
vnLocaleStrings = {};

/**
 * Class to manage the internationalization.
 **/
module.exports =
{
	language: null
	,defaultLang: 'en'
	
	,init: function ()
	{
		if (this.language)
			return;

		var language = this.defaultLang;
		var languages = navigator.languages;

		if (languages && languages.length > 0)
			language = languages[0];
		else if (navigator.language)
			language = navigator.language;

		this.language = language.substr (0, 2);
	}
	
	,load: function (path, callback)
	{
		this.init ();

		var data = {
			path: path,
			callback: callback,
			defOk: false,
			orgOk: this.defaultLang === this.language
		};

		data.def = this.createRequest (data, true, this.defaultLang);

		if (!data.orgOk)
			data.org = this.createRequest (data, false, this.language);
	}

	,createRequest: function (data, isDef, lang)
	{
		var langFile = data.path +'/locale/'+ lang +'.yml'+ Vn.getVersion ();

		var request = new XMLHttpRequest ();
		request.open ('get', langFile, true);
		request.onreadystatechange =
			this.onRequestReady.bind (this, request, data, isDef);
		request.send ();
		return request;
	}

	,onRequestReady: function (request, data, isDef)
	{
		if (request.readyState != 4)
			return;

		if (isDef)
		{
			this.loadFromRequest (request);
			data.defOk = true;
		}
		else
			data.orgOk = true;

		if (data.orgOk && data.defOk)
		{
			if (data.org != null)
				this.loadFromRequest (data.org)
			if (data.callback)
				data.callback ();
		}
	}

	,loadFromRequest: function (request)
	{
		if (request.status !== 200)
			return false;
	
		try {
			this.add (yaml.safeLoad (request.responseText));
			return true;
		}
		catch (e) {
			console.error (e);
		}

		return false
	}
	
	,loadScript: function (path, callback)
	{
		this.init ();
		Vn.includeJs (path +'/locale/'+ this.language, callback);
	}
	
	,add: function (translations)
	{
		for (var str in translations)
			vnLocaleStrings[str] = translations[str];
	}
}

window._ = function (stringId)
{
	var string = vnLocaleStrings[stringId];
	return string ? string : stringId;
}

