angular.module('gms.localization', []).factory('localizationService', function($log, $location ,$locale){
  var localizationService = function(){
    var self = this;
    this.localeJSON = {};

    // Gets the user's language preference from localStorage
    var getLanguageFromServer = function(successHandler, errorHandler){
      $.ajax({
        contentType: "application/x-www-form-urlencoded; charset=UTF-8",
        type: 'GET',
        url: "/genesys/1/admin/preferences/user",
        data: {"key": "language"},
        dataType: "text",
        async: false,
        success: function(data, textStatus, jqXHR) {
          successHandler(data, textStatus, jqXHR);
        },

        error: function(jqXHR, textStatus, errorThrown) {
          errorHandler(jqXHR, textStatus, errorThrown);
        }
      });
    };

    this.getLanguage = function(){
      return localStorage.getItem("locale");
    };

    this.saveLanguagePreference = function(language, successHandler, errorHandler) {
      $.ajax({
        contentType: "application/x-www-form-urlencoded; charset=UTF-8",
        type: 'POST',
        url: "/genesys/1/admin/preferences/user",
        data: {"key": "language", "value": language},
        dataType: "text",
        async: false,
        success: function(data, textStatus, jqXHR) {
          successHandler(data, textStatus, jqXHR);
        },

        error: function(jqXHR, textStatus, errorThrown) {
          //$log.error(textStatus);
          errorHandler(jqXHR, textStatus, errorThrown);
        }
      });
    };

    this.getGMSVersionNumber = function(){
      $.ajax({
        type: 'GET',
        url: "/genesys/1/admin/details",
        dataType: "json",
        success: function(data, textStatus, jqXHR) {
          if(data.version){
              localStorage.setItem("version", data.version);
          }
        },
        error: function(jqXHR, textStatus, errorThrown) {
        }
      });
    };

    //Saves the user's language preference in localStorage
    this.updateLanguage = function(){   
      require.config({
        config: {
          i18n: {
            locale: self.getLanguage(),
          }
        }
      });
    };

    //Gets the locale JSON based on the correct user language preference
    this.getLocaleJSON = function(callback) {      
	  self.updateLanguage();
      require(['i18n!../nls/locale.js'], function(locale){
          	self.localeJSON = locale || {};
          	if(self.localeJSON !== {}){
          		updateAngularLocale();
		      	callback(self.localeJSON);
          	}
      });
    };
    
    //Localize datepicker and other angular-ui-bootsrap-"like" widgets
    function updateAngularLocale(){
    	var angularLocale = {
    			id: self.getLanguage(),
    			DATETIME_FORMATS: self.localeJSON.DATETIME_FORMATS,
    			NUMBER_FORMATS: self.localeJSON.NUMBER_FORMATS
    	};
    	angular.copy(angularLocale, $locale);
    }

    // this.getSupportedLanguages = function(){
    //   var languages = [];
    //     for (var item in self.localeJSON) {
    //       if(self.localeJSON[item] === true){

    //       }
    //     }
    // }
    
    
    //Recursively get json's for the other languages because require is asynchronous.
    //It would be nice to use a synchronous $.get function instead.
    function fetchOtherLanguage(id, array, json, target, callback){
        var path = "../nls/"+ array[id]+"/locale";
        require([path], function(language){
            if(language[target]){
                json[array[id]] = language[target];
            }

            if(id >= array.length -1){
            	if(callback){
                    callback(json);
                }
            } else {
                id++;
                fetchOtherLanguage(id, array, json, target, callback);
            }
        });
    }

    //fetch JSON file into loginJSON
    this.fetchNavBarJSON = function(callback) {
        require(["../nls/locale"], function(locale){
        	var userLang = navigator.language || navigator.userLanguage;
            var languages = [];
            var navBarJSON = {};
            for (var i in locale){
                if(locale[i] === true){                    
                    languages.push(i);
                }
            }
        	//Default to root Language.
            navBarJSON[locale.root.root_language] = locale.root.NavBar;
            if(languages.length > 0){
            	fetchOtherLanguage(0, languages, navBarJSON, 'NavBar', callback);
            } else {
            	if (callback){
            		callback(navBarJSON);
            	}
            }
        });
    };
    
    this.fetchLoginJSON = function(callback) {
        require(["../nls/locale"], function(locale){
        	// Get browser's language.
        	var userLang = navigator.language || navigator.userLanguage;
            var loginJSON = {};
            var languages = [];
            var defaultLang = "";

            // Get the languages that are set to true in the root locale.js
            for (var i in locale){
                if(locale[i] === true){
                    if(userLang === i){
                        defaultLang = i;
                    } else if (userLang.substring(0, 2) === i.substring(0, 2)){
                        defaultLang = i;
                    }
                    
                    languages.push(i);                
                }
            }

            /* 
             * our version of ark-login takes the first language object in loginJSON as the default language
             * so we have to add the various languages in order.
             * 
             * if defaultLang !== "" it means that there are some values in languages array
             * so we move defaultLang to the beginning of the languages array so that the its 
             * localization strings can be added first.
             */
            if (defaultLang !== ""){
                languages.unshift(defaultLang);
                localStorage.setItem("locale", defaultLang);
                require.config({
        	      config: {
        	        i18n: {
        	          locale: defaultLang,
        	        }
        	      }
        	    });
                
                fetchOtherLanguage(0, languages, loginJSON, 'Main_Login', function(){
                    loginJSON[locale.root.root_language] = locale.root.Main_Login;
                    if(callback){
                    	callback(loginJSON);
                    }
                });
            } else {
            	//Default to root Language.
                loginJSON[locale.root.root_language] = locale.root.Main_Login;
                localStorage.setItem("locale", locale.root.root_language);
                require.config({
        	      config: {
        	        i18n: {
        	          locale: locale.root.root_language,
        	        }
        	      }
        	    });
                if(languages.length > 0){
                	fetchOtherLanguage(0, languages, loginJSON, 'Main_Login', callback);
                } else {
                	if (callback){
                		callback(loginJSON);
                	}
                }
            }
        });
    };

  };

  return new localizationService();
});
