'use strict';

angular.module('ark.core').factory(

    'navigationBarService',

    function($log, $resource, $http, $routeParams, $location, $q, localizationService){

        // Private: Event callback collection
        var oEvents = {

            "onJSONUpdate": []
        };

        var NavigationBarService = function(){
            var self = this;
            this.initialized = false;
            this.oNavigationJSON = false;
            this.userName = "";


            this.initialize = function(){
                var deferred = $q.defer();
                this.getUserData(function(data){
                    if (data && data.user && data.user.name){
                      self.userName = data.user.name;
                    }                  
                    self.fetchNavigationJSON(function(){
                      self.initialized = true;
                      deferred.resolve();                      
                    });
                });

                return deferred.promise;
            };

            this.getUserData = function(handler){
                $http({
                  method: 'GET', 
                  url : '/genesys/1/admin/me',
              }).then(function(response) {
                    handler(response.data);
                }, function() {
                    handler();
                });
            };
            
            // JSON Request
            this.fetchNavigationJSON = function(callBack){

                // Custom code here for retrieving the JSON config object to build the navbar
                // NOTE: Be sure to trigger the callBack argument!

                //Fetch the Navigation Bar JSON from the JSON file
                if ($location.$$path === '/cs'){
                  $http.get('app/configuration/navigationBarJSON-cs.json').then(function(response) {
                    let data = response.data;
                    self.setNavigationJSON(data);
                    //LATEST METHOD FOR LOCALIZATION. THIS SHOULD BE USED INSTEAD OF $http.get()
                    localizationService.fetchNavBarJSON(function(data){
                   	//Grab the username from the localStorage
                       if (data[self.getI18n()]['nav_account'] && self.userName){
                         data[self.getI18n()]['nav_account'] = self.userName;
                       }

                      self.oNavigationJSON["i18n"] = data;
                      self.onJSONUpdate();
                      callBack();
                   });
                  });
                } else if ($location.$$path === '/services' || $location.$$path === '/callback' || 
                           $location.$$path === '/service-templates' || $location.$$path === '/patterns' || 
                           $location.$$path === '/resources' || $location.$$path === '/download-dfm' ||
                           $location.$$path === '/monitor' || $location.$$path === '/metrics' ||
                           $location.$$path === '/office-hours' || $location.$$path === '/config'){
                  $http.get('app/configuration/navigationBarJSON-services.json').then(function(response) {
                    let data = response.data;
                    self.setNavigationJSON(data);
                    localizationService.fetchNavBarJSON(function(data){
                      //Grab the username from the localStorage
                        if (data[self.getI18n()]['nav_account'] && self.userName){
                          data[self.getI18n()]['nav_account'] = self.userName;
                        }

                       self.oNavigationJSON["i18n"] = data;
                       self.onJSONUpdate();
                       callBack();
                    });
                  });
                } else if($location.$$path === '/journey-timeline'){
                    $http.get('app/configuration/navigationBarJSON-journey-timeline.json').then(function(response) {
                        let data = response.data
                        self.setNavigationJSON(data);
                        localizationService.fetchNavBarJSON(function(data){
                               //Grab the username from the localStorage
                            if (data[self.getI18n()]['nav_account'] && self.userName){
                              data[self.getI18n()]['nav_account'] = self.userName;
                            }

                           self.oNavigationJSON["i18n"] = data;
                           self.onJSONUpdate();
                           callBack();
                        });
                       });  
                }
                else {
                  $http.get('app/configuration/navigationBarJSON.json').then(function(response) {
                   let data = response.data
                   self.setNavigationJSON(data);
                   localizationService.fetchNavBarJSON(function(data){
                   	   //Grab the username from the localStorage
                       if (data[self.getI18n()]['nav_account'] && self.userName){
                         data[self.getI18n()]['nav_account'] = self.userName;
                       }

                      self.oNavigationJSON["i18n"] = data;
                      self.onJSONUpdate();
                      callBack();
                   });
                  });
                }
            };


            // Setter for JSON
            this.setNavigationJSON = function(navJSON){

                self.oNavigationJSON = navJSON;

                self.onJSONUpdate();
            };

            // Getter for JSON
            this.getNavigationJSON = function(){

                return self.oNavigationJSON;
            };

            // Event for JSON update
            // DO NOT EDIT!
            this.onJSONUpdate = function(fCallback){

                if (fCallback){

                    this.registerEvent("onJSONUpdate", fCallback);

                } else {

                    this.triggerEvent("onJSONUpdate");
                }
            };

            // Pseudo-Event Trigger
            // DO NOT EDIT!
            this.triggerEvent = function(sEventName){

                if(oEvents[sEventName]){

                    for(var i=0; i<oEvents[sEventName].length; i++){

                        oEvents[sEventName][i]();
                    }
                }
            };

            // Pseudo-Event Registration
            // DO NOT EDIT!
            this.registerEvent = function(sEventName, fCallback){

                if(!oEvents[sEventName]){

                    oEvents[sEventName] = [];
                }

                if(fCallback){

                    oEvents[sEventName].push(fCallback);
                }
            };

            // Controls highlighting of NavItems when URL matches selected NavItem
            // Assumes your navigation routing uses the #/main/sub pattern
            // If your app does not use that pattern, you must rewrite this method
            // to parse out the effective main/sub pattern in the same format
            this.matchRoute = function(sRoute){
                var tools = ["service-templates", "resources", "patterns", "download-dfm", "metrics", "config"];

                if(sRoute){
                  var oRoute = sRoute.replace("#/","").split("/"),
                      oLocation = $location.path().replace("#/","").split("/"),
                      oOut = {module: false, subModule: false};

                  oLocation.shift();

                if (oRoute[$routeParams.env ? 1 : 0] === oLocation[$routeParams.env ? 1 : 0]) 
                  oOut.module = true;
                if ((oRoute[$routeParams.env ? 2 : 1] === oLocation[$routeParams.env ? 2 : 1]) && (typeof oRoute[$routeParams.env?2:1] != 'undefined'))
                  oOut.subModule = true;

                if (tools.indexOf(oLocation[$routeParams.env ? 1 : 0]) !== -1 && oRoute[$routeParams.env ? 1 : 0] === "tools"){
                  oOut.module = true;
                }

                  return oOut;
                } else {
                  return null;
                }
              };

            // Getter for language
            this.getI18n = function(){

                // You must make this method return your App's current selected language code
                // If you have a ConfigService object, include it in this service and fetch the
                // language code from that and pass it through in here.
            	var i18n = localizationService.getLanguage();
            	if ($location.$$path === '/cs' || $location.$$path === '/journey-timeline'){
            		// No localization for Context Services and Journey Timeline UI
            		i18n = "en-US";
            	}
            	if(i18n === "en-us"){
            		i18n =  "en-US"
            	}
                return i18n;
            };
        };

        return new NavigationBarService();
    }
);

