/**
 Description: Switch Controller. Can broadcast the event called as 'portSelected' on rootScope.
 Copyright (c) 2016 by Cisco Systems, Inc.
 All rights reserved.
 */
'use strict';

app.controller('switchCtrl4Stack', ['$scope', '$rootScope', '$filter', '$interval', 'notificationService','requestRoutingService','dialogService','switchDataService4Stack','dashletReloadTime','$timeout',
function($scope, $rootScope, $filter, $interval, notificationService, requestRoutingService, dialogService, switchDataService4Stack,dashletReloadTime,$timeout) {
	var translate = $filter("translate");
	$scope.showModeButtons = false;
	$scope.fetchDataUrl = ( runFromLocalhost ? "resources/data/switch.json" : "switch");
	$scope.memberToDel = "";	
	$scope.memberToAdd = "";	
	$scope.switchId = "";	
	$scope.memberToRestart = "";
	//Function to fetch the data from the switch in the required JSON format
	var fetchData = function(){
		return switchDataService4Stack.getSwitchViewData($scope); 
	};

	//Fetch data to show the switch view
	$scope.switchData = fetchData();

	//Refresh the switch view every 60 seconds
	var switchViewFetchLoop = $interval(function(){
		if(angular.element(".switchGraph").length > 0){
			$scope.switchData = fetchData();
		} else {
			$interval.cancel(switchViewFetchLoop);
		}
	}, dashletReloadTime);
	
	$scope.findProperty = function(obj, objProp){
		if(obj.hasOwnProperty(objProp)){
			return true;
		}
		return false;
	}
	//The following JSON is a sample for dashboard. In case of any doubt,
	// or debugging, this data can be used as test data instead of fetching it above
	/*{
		"hostname" : "switch123",
		"noOfSwitches" : 2,
		"masterSwitchId" : 1,
		"switches" : [{
			"id" : 1,
			"macAdd" : "aa:bb:cc:dd:ee:ef",
			"isPoECapable" : true,
			"isStackConfigurable" : false,
			"ports" : [[[{
				"portNo" : 1,
				"uniqueId" : "Gi1/0/1",
				"duplex" : true,
				"poe" : true,
				"power": 10,
				"status" : 1,
				"speed" : 10
			}, {
				"portNo" : 2,
				"uniqueId" : "Gi1/0/2",
				"duplex" : true,
				"poe" : true,
				"status" : 2,
				"speed" : 100
			}], [{
				"portNo" : 3,
				"uniqueId" : "Gi1/0/3",
				"duplex" : false,
				"poe" : true,
				"status" : 1,
				"speed" : 100
			}, {
				"portNo" : 4,
				"uniqueId" : "Gi1/0/4",
				"duplex" : true,
				"poe" : true,
				"status" : 1,
				"speed" : 1000
			}], [{
				"portNo" : 5,
				"uniqueId" : "Gi1/0/3",
				"duplex" : false,
				"poe" : true,
				"status" : 1,
				"speed" : 1000
			}, {
				"portNo" : 6,
				"uniqueId" : "Gi1/0/4",
				"duplex" : true,
				"poe" : true,
				"status" : 1,
				"speed" : 1000
			}], [{
				"portNo" : 7,
				"uniqueId" : "Gi1/0/3",
				"duplex" : true,
				"poe" : true,
				"status" : 1,
				"speed" : 1000
			}, {
				"portNo" : 8,
				"uniqueId" : "Gi1/0/4",
				"duplex" : true,
				"poe" : true,
				"status" : 1,
				"speed" : 1000
			}]], [[{
				"portNo" : 9,
				"uniqueId" : "Gi1/0/5",
				"duplex" : true,
				"poe" : true,
				"status" : 1,
				"speed" : 1000
			}, {
				"portNo" : 10,
				"uniqueId" : "Gi1/0/6",
				"duplex" : true,
				"poe" : true,
				"status" : 0,
				"speed" : 1000
			}], [{
				"portNo" : 11,
				"uniqueId" : "Gi1/0/7",
				"duplex" : true,
				"poe" : false,
				"status" : 0,
				"speed" : 100
			}, {
				"portNo" : 12,
				"uniqueId" : "Gi1/0/1",
				"duplex" : true,
				"poe" : false,
				"status" : 0,
				"speed" : 100
			}], [{
				"portNo" : 13,
				"uniqueId" : "Gi1/0/3",
				"duplex" : true,
				"poe" : true,
				"status" : 1,
				"speed" : 1000
			}, {
				"portNo" : 14,
				"uniqueId" : "Gi1/0/4",
				"duplex" : true,
				"poe" : true,
				"status" : 1,
				"speed" : 1000
			}], [{
				"portNo" : 15,
				"uniqueId" : "Gi1/0/3",
				"duplex" : true,
				"poe" : true,
				"status" : 1,
				"speed" : 1000
			}, {
				"portNo" : 16,
				"uniqueId" : "Gi1/0/4",
				"duplex" : true,
				"poe" : true,
				"status" : 1,
				"speed" : 1000
			}]]],
			"uplinkports" : [{
				"portNo" : 15,
				"uniqueId" : "Gi1/0/15",
				"duplex" : true,
				"status" : 0,
				"speed" : 1000
			}, {
				"portNo" : 16,
				"uniqueId" : "Gi1/0/16",
				"duplex" : true,
				"status" : 0,
				"speed" : 1000
			}]
		},{
			"id" : 2,
			"macAdd" : "aa:bb:cc:dd:ee:ef",
			"isPoECapable" : true,
			"isStackConfigurable" : true,
			"ports" : [[[{
				"portNo" : 1,
				"uniqueId" : "Gi1/0/1",
				"duplex" : true,
				"poe" : true,
				"status" : 1,
				"speed" : 1000
			}, {
				"portNo" : 2,
				"uniqueId" : "Gi1/0/2",
				"duplex" : true,
				"poe" : true,
				"status" : 1,
				"speed" : 1000
			}], [{
				"portNo" : 3,
				"uniqueId" : "Gi1/0/3",
				"duplex" : true,
				"poe" : true,
				"status" : 1,
				"speed" : 1000
			}, {
				"portNo" : 4,
				"uniqueId" : "Gi1/0/4",
				"duplex" : true,
				"poe" : true,
				"status" : 1,
				"speed" : 1000
			}], [{
				"portNo" : 5,
				"uniqueId" : "Gi1/0/3",
				"duplex" : true,
				"poe" : true,
				"status" : 1,
				"speed" : 1000
			}, {
				"portNo" : 6,
				"uniqueId" : "Gi1/0/4",
				"duplex" : true,
				"poe" : true,
				"status" : 1,
				"speed" : 1000
			}], [{
				"portNo" : 7,
				"uniqueId" : "Gi1/0/3",
				"duplex" : true,
				"poe" : true,
				"status" : 1,
				"speed" : 1000
			}, {
				"portNo" : 8,
				"uniqueId" : "Gi1/0/4",
				"duplex" : true,
				"poe" : true,
				"status" : 1,
				"speed" : 1000
			}]], [[{
				"portNo" : 9,
				"uniqueId" : "Gi1/0/5",
				"duplex" : true,
				"poe" : true,
				"status" : 1,
				"speed" : 1000
			}, {
				"portNo" : 10,
				"uniqueId" : "Gi1/0/6",
				"duplex" : true,
				"poe" : true,
				"status" : 0,
				"speed" : 1000
			}], [{
				"portNo" : 11,
				"uniqueId" : "Gi1/0/7",
				"duplex" : false,
				"poe" : false,
				"status" : 0,
				"speed" : 100
			}, {
				"portNo" : 12,
				"uniqueId" : "Gi1/0/1",
				"duplex" : true,
				"poe" : false,
				"status" : 0,
				"speed" : 100
			}], [{
				"portNo" : 13,
				"uniqueId" : "Gi1/0/3",
				"duplex" : false,
				"poe" : true,
				"status" : 1,
				"speed" : 1000
			}, {
				"portNo" : 14,
				"uniqueId" : "Gi1/0/4",
				"duplex" : true,
				"poe" : true,
				"status" : 1,
				"speed" : 1000
			}], [{
				"portNo" : 15,
				"uniqueId" : "Gi1/0/3",
				"duplex" : true,
				"poe" : true,
				"status" : 1,
				"speed" : 1000
			}, {
				"portNo" : 16,
				"uniqueId" : "Gi1/0/4",
				"duplex" : true,
				"poe" : true,
				"status" : 1,
				"speed" : 1000
			}]]],
			"uplinkports" : [{
				"portNo" : 15,
				"uniqueId" : "Gi1/0/15",
				"duplex" : true,
				"status" : 0,
				"speed" : 1000
			}, {
				"portNo" : 16,
				"uniqueId" : "Gi1/0/16",
				"duplex" : true,
				"status" : 0,
				"speed" : 1000
			}]
		}]
	};*/

	$scope.$on("addMemberToCluster", function(event, data) {
                $scope.dlg.data("kendoWindow").close();
		var result ="";
                if(document.getElementById("password").value != ""){
		 	result = requestRoutingService.getConfigCmdOutput("cluster member mac-address " + $scope.memberToAdd
								+ " password " + document.getElementById("password").value);		
                } else{
		 	result = requestRoutingService.getConfigCmdOutput("cluster member mac-address " + $scope.memberToAdd );
                }
		if(result == ""){
			notificationService.showNotification(translate('cluster_add_success'),translate('com_config_success_title'),'success');
			//Update the view data
			$scope.switchData = fetchData();
		} else {
			notificationService.showNotification(result.errorResponse,translate('com_config_fail_title'),'error');
			$scope.showPasswordDialog($scope.memberToAdd);
		}
        });	

	$scope.$on("deleteMemberFromCluster", function(event, data) {
                $scope.dlg.data("kendoWindow").close();
                var result = requestRoutingService.getConfigCmdOutput("no cluster member " + $scope.memberToDel );
                if(result == ""){
                        notificationService.showNotification(translate('cluster_del_success'),translate('com_config_success_title'),'success');
                        //Update the view data
                        $scope.switchData = fetchData();
                } else {
                        notificationService.showNotification(result.errorResponse,translate('com_config_fail_title'),'error');
                }
        });
	
	$scope.showStatus = function(event, status){
		angular.element(".actionInput").removeClass("selected");
		angular.element(event.target).parents(".actionInput").addClass("selected");
		angular.element(event.target).parents(".switchContainer").removeClass("duplex stat stack poe speed").addClass(status)
	};

	//Function to RESTART a specific switch in the cluster
	$scope.showRestartConfirmDialog = function(switchId,macAdd){
                console.log("in restart");
		if(macAdd === $rootScope.deviceInfo.baseMacAdd){
			switchId = "";
		}
		$scope.switchId = switchId;
                $scope.dlg = dialogService.dialog({
                        content : translate('restart_confirm') + "<br/>"+ "<div class=\"col-sm-9 col-sm-offset-1 webui-centerpanel-label\"><div class=\"col-sm-4 custom-checkbox\"><span class=\"label\">"+translate('save_configuration')+"</span></div><div class=\"col-sm-1 custom-checkbox\"><input type=\"checkbox\" name=\"saveconfig\" id=\"saveconfig\" class=\"k-checkbox form-control\" ng-model=\"saveconfig\"><label class=\"k-checkbox-label\" for=\"saveconfig\"></label></div></div>" + "<br/>",
                        title : translate('software_update_restart_title'),
                        messageType : "confirm",
                        actionButtons : [{
                                text : translate("com_ok"),
                                callback : "restartSwitch"
                        }, {
                                text : translate("com_cancel")
                        }]
                });
        };
	$scope.$on("restartSwitch", function(event, data) {
                $scope.dlg.data("kendoWindow").close();
		var cli = "";
		var stackMemberDetails = "";
		if($scope.switchId != ""){
			if($rootScope.deviceInfo.stackingInfo.type == "CLUSTER"){
				cli+="rcommand " + $scope.switchId + "\n";
			}else{
				stackMemberDetails = " slot " + $scope.switchId;
			}
		}
                if(angular.element("#saveconfig").is(":checked")){
			cli+="write memory\n reload" + stackMemberDetails + "\n";
                } else{
			cli+="reload"+ stackMemberDetails + "\n";
                }
                var result = requestRoutingService.getShowCmdOutput(cli);
		if(result = ""){
			notificationService.showNotification(translate('restart_success'),translate('software_update_restart_title'),'success');
		} else {
			notificationService.showNotification(result.errorResponse,translate('restart_fail'),'error');
		}
        });

	//Function to ADD a specific switch to the cluster
	$scope.showPasswordDialog = function(macAddress){
                console.log("in restart");
		$scope.memberToAdd = macAddress;
                $scope.dlg = dialogService.dialog({
                        content : translate('stack_virtual_member_confirm') + "<br/>"+"<div class=\"col-sm-4 \"><input type=\"password\" name=\"enablesecret\" id=\"password\" class=\"k-textbox form-control\" ng-model=\"enablesecret\"></div>" + "<br/>",
                        title : translate('day0_wizard_basic_config_password'),
                        messageType : "confirm",
                        actionButtons : [{
                                text : translate("com_ok"),
                                callback : "addMemberToCluster"
                        }, {
                                text : translate("com_cancel")
                        }]
                });
	};	

	//Function to DELETE a specific switch from the cluster
	$scope.deleteMemberConfirm = function(switchId){
		$scope.memberToDel = switchId;
		$scope.dlg = dialogService.dialog({
                        content : translate('help_stacking_delete_member'),
                        title : translate('com_delete'),
                        messageType : "confirm",
                        actionButtons : [{
                                text : translate("com_ok"),
                                callback : "deleteMemberFromCluster"
                        }, {
                                text : translate("com_cancel")
                        }]
                });	
	};
	$scope.setTitle = function(event, fromWhere){
		var elmt = angular.element(event.target),
		prnt = elmt.parents(".switchContainer"),
		prtData = elmt.parents(".portData"),
		allPortData = angular.fromJson(elmt.parents(".portData").attr("data-port"));
		/*
		if(prnt.hasClass("stat") && prtData.attr("data-status") == "1"){
			elmt.attr("title", "Status: Up");
		} else if(prnt.hasClass("stat") && prtData.attr("data-status") == "0"){
			elmt.attr("title", "Status: Down");
		} else if(prnt.hasClass("stat") && prtData.attr("data-status") == "2"){
			elmt.attr("title", "Status: Administrative Down");
		} else if(prnt.hasClass("duplex") && prtData.attr("data-duplex") == "true"){
			elmt.attr("title", "Enabled Duplex Mode");
		} else if(prnt.hasClass("duplex") && prtData.attr("data-duplex") == "false"){
			elmt.attr("title", "Disabled Duplex Mode");
		} else if(prnt.hasClass("stack") && prtData.attr("data-stack") == "1"){
			elmt.attr("title", "stack Title");
		} else if(prnt.hasClass("poe") && prtData.attr("data-poe") == "true"){
			elmt.attr("title", "Power Drawn: "+(allPortData.power||0) + " Watts");
		} else if(prnt.hasClass("poe") && prtData.attr("data-poe") == "false"){
			elmt.attr("title", "No Power Drawn");
		} else if(prnt.hasClass("speed") && (prtData.attr("data-speed") == "10"||prtData.attr("data-speed") == "100"||prtData.attr("data-speed") == "1000")){
			elmt.attr("title", translate("switch_speed_title").replace("{0}", prtData.attr("data-speed")));
		} else{
			elmt.attr("title", "No Link");
		}
		*/
		var titleString="";
		if(fromWhere){
			allPortData = angular.fromJson(elmt.attr("data-port"));
			titleString = translate('tbl_column_portname') + ": " + allPortData.uniqueId + '\n' +
				   translate('switch_status_title').replace("{0}", $rootScope.portStatus[parseInt(allPortData.status)]) + '\n' +
                                   translate('switch_speed_title').replace("{0}", allPortData.speed) + '\n' +
                                   translate('switch_duplex_title').replace("{0}", allPortData.duplex) + '\n';
		}else{
			titleString = translate('tbl_column_portname') + ": " + allPortData.uniqueId + '\n' +
				   translate('switch_status_title').replace("{0}", $rootScope.portStatus[parseInt(prtData.attr("data-status"))]) + '\n' + 
				   translate('switch_speed_title').replace("{0}", prtData.attr("data-speed")) + '\n' + 
				   translate('switch_duplex_title').replace("{0}", prtData.attr("data-duplex")) + '\n' +
				   translate('switch_power_title').replace("{0}",(allPortData.power||0));
		}
		elmt.attr("title", titleString);
	};
   
       $scope.handleClickOnPort = function(event, portNum){
		/* Broadcast an event, 'portSelected'. This event can be captured in
		   any of the controllers, under root scope, and the corresponding row
    		   can be lighlighted or used in any other way.
                */
				if(angular.element(event.target).css("cursor") == "pointer"){
					$rootScope.portNumIdentity = portNum;
				}
                var args = {};
                args.event = event;
                args.object = this.portObj || this.uplinkObj; //Ethernet ports or Uplink ports, common event
                $rootScope.$broadcast('portSelected',args);
       };
}]);
