/// <reference path="../references.js" />

rwthapp.localization = (function () {
    var defaultLanguage = rwthapp.options.getDefaultLanguage();
	var currentLanguage = defaultLanguage;
	var availableLanguages = [
            { id: 'en', name: 'English' },
            { id: 'de', name: 'Deutsch' }
	];
    // Initialise persistent storage
	var storage = new rwthapp.Storage("localization");
	storage.addAttribute("currentLanguage");

	var getLocalizedString = function (key) {
	    return rwthapp.util.getPropertyByString(rwthapp.langStrings, key);
	};

	var setLanguage = function (lang, persist) {
	    var newLanguage = getValidLangString(lang);

        // Only load new language if language data is available
	    if (rwthapp.languages[newLanguage]) {
	        currentLanguage = newLanguage;
	        rwthapp.langStrings = rwthapp.languages[newLanguage];

	        if (persist === true) {
	            storage.setCurrentLanguage(currentLanguage);
	        }
	    } 
	};

	var getValidLangString = function (lang) {
	    if (lang === undefined) {
	        lang = "";
	    }

	    lang = lang.toLowerCase();
	    if (lang === "en" || lang === "english" || lang === "us" || /^en(-[a-z]+)?/.test(lang)) {
	        lang = "en";
	    } else if (lang === "de" || lang === "german" || lang === "deutsch" || /^de(-[a-z]+)?/.test(lang)) {
	        lang = "de";
	    } else {
	        lang = defaultLanguage;
	    }

	    return lang;
	};

	var getCurrentLanguage = function () {
		return currentLanguage;
	};

	var loadPreferredLanguage = function () {
		// If the language was already defined by the user -> use this language
		if (storage.getCurrentLanguage() !== undefined && storage.getCurrentLanguage() !== null) {
			// Set the language
			setLanguage(storage.getCurrentLanguage(), false);
		} else {
			// Get the language through the globalization plugin
			navigator.globalization.getPreferredLanguage(function (data) {
				setLanguage(data.value, false);
			}, function () {
				setLanguage(defaultLanguage, false);
			});
		}
	};

	var handlebarsLangStringHelper = function (key, fallbackString) {
		var localizedString = getLocalizedString(key);
		if(typeof localizedString === "string" && localizedString !== null && localizedString !== "") {
			return localizedString;
		} else if (typeof fallbackString === "string") {
			return fallbackString;
		}

		return "";
	};

	var getAvailableLanguages = function () {
	    // Create deep copy
	    return $.extend(true, [], availableLanguages);
	};

	return {
		getLocalizedString: getLocalizedString,
		setLanguage: setLanguage,
		getCurrentLanguage: getCurrentLanguage,
		loadPreferredLanguage: loadPreferredLanguage,
		handlebarsLangStringHelper: handlebarsLangStringHelper,
        getAvailableLanguages: getAvailableLanguages
	};
})();