/**
 Description: Header Controller
 Copyright (c) 2016 by Cisco Systems, Inc.
 All rights reserved.
 */
app.controller("headerCtrl", ['$rootScope', '$scope', '$filter', '$location', '$timeout', 'onlineHelpService', 
		'dialogService','notificationService','requestRoutingService', 
		function($rootScope, $scope, $filter, $location, $timeout, onlineHelpService, dialogService, 
		notificationService,requestRoutingService) {
	
	var translate = $filter("translate");
	//Set Language related configs
	//Add any new supported language here and in i18nService in commonServices.js
	//Set default language
	$scope.prefLang = null;
	$scope.isLoading = true;
	//The drop down takes a while to populate. We cannot time it. Hence try till its populated and call it.
	var setDefaultLanguage = function(){
		$timeout(function () {
			if(angular.element("#languageSelector").data("kendoDropDownList") && 
				angular.element("#languageSelector").data("kendoDropDownList").dataSource._data.length){
				$scope.prefLang = $rootScope.preferredLanguage;
			} else {
				setDefaultLanguage();
			}
        	}, 500);
	};
	setDefaultLanguage();
	$scope.supportedLanguages = new kendo.data.ObservableArray([
                                {"name": "English", "value": "en"},
                                {"name": "中文", "value": "zh"},
                                {"name": "日本語", "value": "ja"},
                                {"name": "한국어", "value": "ko"}
                        ]);
	$scope.updateLanguageSelection = function(){
		if($scope.isLoading){
			$scope.isLoading=!$scope.isLoading;
			return;
		}
		if(this.prefLang !== $rootScope.preferredLanguage){
			angular.element("body").addClass("busy");
			window.localStorage.preferredLanguage = this.prefLang;
			window.location.reload();
		}
	};

	//Set device description and device Version
	var versionInfo = requestRoutingService.getShowCmdOutput("show version","overviewshVer");
	$scope.version = versionInfo.ShowVersion.version.split(',')[0]; //Remove the "," at the end
	$scope.deviceDescription = versionInfo.ShowVersion.name;

	$rootScope.userPrivilegeLevel = parseInt(requestRoutingService.getShowCmdOutput("show privilege").substr(27));
	var hostname = deviceCommunicator.getExecCmdOutput("show running-config | i hostname"); 
	$rootScope.hostName = hostname.split("\r\n")[0].substr(9);
	$rootScope.portStatus = ['not connected','connected','disabled','error-disabled'];
	$scope.isActive = false;
	$scope.hideShowMenu = function() {
		$scope.isActive = !$scope.isActive;
		$rootScope.$broadcast('hideShowMegaMenu', {"isActive": $scope.isActive});
	};
	
	setTimeout(function(){
		onlineHelpService.setBrowserTitle($location.url(), $scope.deviceDescription, " ");
	}, 500);

	$scope.$on('$locationChangeSuccess', function(event, url) {
		var url = $location.url();
		$scope.currentPage = url;
		// Setting the browser title
		if(!$rootScope.hostName){
				$rootScope.hostName = "Switch";
		}
		setTimeout(function(){
			onlineHelpService.setBrowserTitle($scope.currentPage, $scope.deviceDescription, " ");
		}, 500);
		
	});
	
	$scope.openOnlineHelpWindow = function() {
		//var helpPageUrl = "https://www.cisco.com/c/en/us/td/docs/switches/lan/catalyst2960l/software/15-2_5_e/configuration_guide/b-1525E-ios-classic-gui-cg.html";
		var helpPageUrl = "https://www.cisco.com/c/en/us/td/docs/switches/lan/cisco_cpc/release_1_1/ui_config_guide/b-ccpc-1-1-cg.html";
		onlineHelpService.openExternalHelpWindow(helpPageUrl);
	};
	
	$scope.showConfirmWindow = function(value, window) {
		if (value) {
			window.center().open();
		} else {
			window.close();
		}
	};
	
	$scope.logout = function() {
		window.location.href = "/webui/logout.html";
	};
	
	$scope.$on("okClicked_logout", function(event, data) {
		if($scope.dlg){
			$scope.dlg.data("kendoWindow").close();
			$scope.logout();
		}
	});
	
	$scope.$on("okClicked_saveConfiguration", function(event, data) {
		if($scope.dlg){
			var result = requestRoutingService.getShowCmdOutput("write memory");
	                if(result != undefined && result.indexOf("[OK]")){
            		  notificationService.showNotification(translate('saveconfig_success_msg'), translate('saveconfig_success'), 'success');
            		}else{
               		  notificationService.showNotification(translate('saveconfig_fail_msg'), translate('saveconfig_fail'), 'error');
            		}
			$scope.dlg.data("kendoWindow").close();
		}
	});
	
	$scope.showWindow = function(windowFor) {
		if (windowFor == "logoutConfirmWindow") {
			$scope.dlg = dialogService.dialog({
				content : translate("msg_logout"),
				title : translate("com_logout"),
				messageType : "confirm",
				actionButtons : [{
					text : translate("com_ok"),
					callback : "okClicked_logout"
				}, {
					text : translate("com_cancel")
				}]
			});
		} else if (windowFor == "saveConfigConfirmWindow") {
			$scope.dlg = dialogService.dialog({
				//content : 'Are you sure you want to save the configuration?',
				content : translate('confirm_save_config'),
				title : translate('save_configuration'),
				messageType : "confirm",
				actionButtons : [{
					text : translate("com_ok"),
					callback : "okClicked_saveConfiguration",
					btnClass : "dummyClass"
				}, {
					text : translate("com_cancel")
				}]
			});
		} else if (windowFor === "systemInformationWindow") {
			var message = properties.productName +" (" + properties.productNameShort + ")" +
					"\nVersion: "+webuiVersionInfo.version +
					"\nBuilt: "+webuiVersionInfo.buildTime; 
			var copyRight = properties.productNameShort +
					"\n"+properties.copyRight+"\n"; 
			
			$scope.dlg = dialogService.sysInfoDialog({
                                content : message,
				copyRight : copyRight,
                                title : translate('product_information'),
                                messageType : "confirm",
                                actionButtons : [{
                                        text : translate("com_ok"),
                                        btnClass : "dummyClass"
                                }]
                        });
		}
	};
	
	$scope.isIE = function() {
		return angular.element("html.k-ie").length;
	};

	$scope.isHTML5SupportedBrowser = function() {
		var createCanvas = document.createElement("canvas");
		var canvascheck = (createCanvas.getContext) ? true : false;
		if (window.FormData == undefined || !canvascheck) {
			return false;
		}
		delete createCanvas;
		return true;
	};
	
}]);

