/**
 Description: Controller for Trouble Shooting
 Copyright (c) 2016 by Cisco Systems, Inc.
 All rights reserved.
 */
app.controller('troubleShootCtrl', ['$scope','$rootScope','$filter', 'gridCrudService','requestRoutingService','executeCliCmdService','$timeout','executeCliCmdService','getStringLineService','dialogService',
	function($scope,$rootScope,$filter, gridCrudService,requestRoutingService,executeCliCmdService,$timeout,executeCliCmdService,getStringLineService,dialogService) {
		var translate = $filter("translate");	
		$scope.statusMsg="";
		$scope.showTick = true;
		var chartStatus=0;
		$scope.pingSource="";
		$scope.diagnosticTest="";
				
		// Ping validation
		var pingValidations = angular.element("#pingForm").kendoValidator({
			rules: {				
			}
		}).data("kendoValidator");
		
		if($rootScope.deviceInfo.type.indexOf("CDB")!=-1){   
			$scope.showConnectCtrl = true;
		}
				
		$scope.showRebootConfirmDialog = function(input){
			$scope.dlg = dialogService.dialog({
				content : translate('factory_reset_confirm') + "<br/>"+ "<div class=\"col-sm-9 col-sm-offset-1 webui-centerpanel-label\"></div>" + "<br/>",
				title : translate('software_update_restart_title'),
				messageType : "confirm",
				actionButtons : [{
					text : translate("com_ok"),
					callback : "RebootSwitch"
				}, {
					text : translate("com_cancel")
				}]
			});
		};
		
		$scope.$on("RebootSwitch", function(event, data) {
			$scope.dlg.data("kendoWindow").close();
			var x= $scope.showRestartSuccessDialog();
			if($rootScope.deviceInfo.type.indexOf("CDB")!=-1){     
				requestRoutingService.getShowCmdOutput("staging standalone\n");
				requestRoutingService.getShowCmdOutput("write erase\n");
				requestRoutingService.getShowCmdOutput("reload\n");
			}else{					
				requestRoutingService.getShowCmdOutput("write erase\n");
				requestRoutingService.getShowCmdOutput("reload\n");
			}
		});
		
		$scope.showRestartSuccessDialog = function(input){
			$scope.dlg = dialogService.dialog({
				content : translate('software_update_restart_success'),
				title : translate('software_update_restart_title'),
				messageType : "success",
				actionButtons : [{
					text : translate("com_ok")
				}]
			});
		};
		
		$scope.showConnectController = function(){
			if($rootScope.deviceInfo.type.indexOf("CDB")!=-1){     
				requestRoutingService.getShowCmdOutput("staging network\n");
			}
		}
		
		//load interface with configured ip address
		$scope.pingSourceInterface=[];
		$scope.loadInterfaces = function(){
	        var showInterfaces = requestRoutingService.getShowCmdOutput("show ip int brief", "showInterfaces");
	        showInterfaces = showInterfaces.showIpInterfaceBrief.IntBriefTable.entry;
	        var pingSourceInterface = {
					"intNameAddress": "none",
    				"name":"none"
    		};
    		$scope.pingSourceInterface.push(pingSourceInterface); 
	        angular.forEach(showInterfaces, function(interfaces, index){
	        	if(interfaces.ipAddress != 'unassigned'){
	        			var pingSourceInterface = {
	        					"intNameAddress": interfaces.interfaceName+"-"+interfaces.ipAddress,  				
		        				"name":interfaces.interfaceName
		        		};
		        		$scope.pingSourceInterface.push(pingSourceInterface);        			
	        	}
	        });	        					
	    }
	    $scope.loadInterfaces();
		
       $scope.startPing= function(evt) {
          evt=evt.target;
          $scope.statusMsg="";
          $scope.isChartShown = false;
          chartStatus=0;
        	       	
         if(pingValidations.validate()){ 
        	 angular.element(evt).button('loading');
             $scope.showTick = false;
        	
        	var maxRate,minRate,averageRate=0,pingCLI="";
        	$timeout(function() {        		
        		if($scope.pingName!="" && $scope.pingSource!="none"){
        			pingCLI="ping "+$scope.pingName+" source "+$scope.pingSource+"\n";
        		}else{
        			pingCLI="ping "+$scope.pingName+"\n";
        		}
        		var strCLIOutput = deviceCommunicator.getExecCmdOutput(pingCLI);		
        		angular.element(evt).button('reset');
                $scope.showTick = true;
        	       	
        	if(strCLIOutput.indexOf("Success rate is")!=-1){
	            var SUCCESS_OUTPUT_BEGIN = new Array("Success rate is "); 
	            var SUCCESS_OUTPUT_END = new Array("percent");
	            var successStatusPer = executeCliCmdService.getNextString(strCLIOutput,SUCCESS_OUTPUT_BEGIN,SUCCESS_OUTPUT_END);
	            
	            var SUCCESSRATE_OUTPUT_BEGIN = new Array("min/avg/max = "); 
	            var SUCCESSRATE_OUTPUT_END = new Array(" ms");
	            var successRate = executeCliCmdService.getNextString(strCLIOutput,SUCCESSRATE_OUTPUT_BEGIN,SUCCESSRATE_OUTPUT_END);
	            var successRateArr=successRate.split("/");
	           
	            maxRate=successRateArr[2];
	            averageRate=successRateArr[1];
	            minRate=successRateArr[0];
	            if(successStatusPer==0){
	            	$scope.statusMsg=translate("trouble_shoot_noreply_received")+" "+$scope.pingName;
	            }else{
	            	$scope.statusMsg=translate("trouble_shoot_success_rate")+":"+successStatusPer+" %";
	            	chartStatus=1;	            	
	            	$scope.isChartShown = true
	            }           
        	}else if(strCLIOutput.indexOf("Unrecognized host or address, or protocol not running")!=-1){
        		$scope.statusMsg=translate("trouble_shoot_unrecognized");
        	}else if(strCLIOutput.indexOf("Invalid source interface")!=-1){
        		$scope.statusMsg=translate("trouble_shoot_invalid_source");
        	} else {
        		$scope.statusMsg=translate("trouble_shoot_noreply_received")+" "+$scope.pingName;
        	}           
           
        	if(chartStatus==1){
            angular.element("#chart").kendoChart({
                title: {
                    text:translate("trouble_shoot_ping_type")
                },
                chartArea:{                
                    height:300,
                    width :250
                },
                seriesColors: ["#9EC654","#0096D6","#725D87"],
                seriesDefaults: {
	                type: "column",
	                "overlay" : {
	                    "gradient" : "none"
	                }
	            },
                legend: {
                    position: "bottom"
                },                
                series: [{
                    name:translate("trouble_shoot_ping_min"),
                    data: [minRate]
                }, {
                    name:translate("trouble_shoot_ping_avg"),
                    data: [averageRate]
                }, {
                    name:translate("trouble_shoot_ping_max"),
                    data: [maxRate]
                }],
                valueAxis: {
                    labels: {
                        format: "{0} ms"
                    },
                    line: {
                        visible: true
                    },
                    axisCrossingValue: 0
                },
                categoryAxis: {                   
                    line: {
                        visible: false
                    },
                    labels: {
                        padding: {top: 135}
                    }
                },
                tooltip: {
                    visible: true,                    
                    template: "#= series.name #: #= value # ms"
                }
            });
        	}
        	},50);
        }		
      }
       
     //Trace Route code  
    // Ping validation
		var traceRouteValidations = angular.element("#traceRouteForm").kendoValidator({
			rules: {				
			}
		}).data("kendoValidator");
		
       $scope.startTraceRoute= function(evt) {
          evt=evt.target;
          if(traceRouteValidations.validate()){  
          angular.element(evt).button('loading');
          $scope.showTick = false;
          $scope.isTraceRouteGrid = false;
          $timeout(function() {         	    		 
      		  var strCLIOutput = deviceCommunicator.getExecCmdOutput("traceroute "+$scope.traceRouteName+"\n");
	          angular.element(evt).button('reset');
	          $scope.showTick = true;
	          
	           var arrTraceRouteDetails = new Array();
	           var arrWords = new Array();
	           var arrWords1 = new Array();
	           var arrDelays = new Array();
	           var LINE_INDEX = new Array("msec");
	           var strLines = getStringLineService.getLines(strCLIOutput,LINE_INDEX);
	           if (strLines != null) {
	              for (var i=0; i<strLines.length; i++) {            	      
	                      var strLine = strLines[i];
	                      if(strLine.indexOf(")")!=-1){
	                          arrWords = strLine.split(")"); 
	                          arrWords1 = arrWords[0].split("(");
	                          arrDelays = arrWords[1].split(" ");
	                          var items = {
	                          		"hop"          : arrWords1[1],
	                          		"roundTrip1"   : arrDelays[1],
	                          		"roundTrip2"   : arrDelays[3],
	                          		"roundTrip3"   : arrDelays[5]
	                          };                
	                          arrTraceRouteDetails.push(items);                           	 
	                       } else{
	                    	   arrWords = strLine.split(" ");   
	                    	   var items = {
	                           		"hop"          : arrWords[3],
	                           		"roundTrip1"   : arrWords[4],
	                           		"roundTrip2"   : arrWords[6],
	                           		"roundTrip3"   : arrWords[8]
	                           };                
	                           arrTraceRouteDetails.push(items); 
	                       }   
	                 } 
	           }
	           $scope.isTraceRouteGrid = true;	
	           $scope.arrTracesList = new kendo.data.ObservableArray(arrTraceRouteDetails)
	                   $scope.traceRouteDataSource = new kendo.data.DataSource({
	                           pageSize : 20,
	                           data : $scope.arrTracesList
	           });	
	           $scope.traceRouteGridOptions = {
	                   dataSource: $scope.traceRouteDataSource,
	                   editable : false,
	                   sortable : true,
	                   reorderable: true,
	                   scrollable: true,
	                   filterable : {          
	                           extra : false,
	                           operators : {
	                                   string : {
	                                           eq : translate("com_is_equal"),
	                                           neq : translate("com_isnot_equal")
	                                   }
	                           },
	                           messages : {
	           		            info: translate("com_page_dropDowntext"),
	           		            filter: translate("com_btn_filter"),
	           		            clear: translate("com_btn_clear")
	           		        }
	                   },
	                   selectable : true,
	                   pageable : {
	                   		messages: {
	                   			display: translate("com_page_display"), 
	                   			empty: translate("com_page_empty"),
	                   			page: translate("com_page_pagetext"),
	                   			of:translate("com_page_of"),  
	                   			itemsPerPage: translate("com_page_itemsPerPage"),
	                   			first: translate("com_page_first"),
	                   			previous: translate("com_page_previous"),
	                   			next: translate("com_page_next"),
	                   			last: translate("com_page_last"),
	                   			refresh: translate("com_page_refresh"),
	                   			morePages: translate("com_page_morePage")
	                   		},
	                           previousNext : true,
	                           info : true,
	                           refresh : true,
	                           pageSizes : gridCrudService.grid_page_sizes,
	                           buttonCount : 5
	                   },
	                   columns : [{
	                           field : "hop",
	                           title : translate("trouble_shoot_traceroute_hop")
	                   }, {
	                           field : "roundTrip1",
	                           title : translate("trouble_shoot_traceroute_roundtrip")
	                   }, {
	                           field : "roundTrip2",
	                           title : translate("trouble_shoot_traceroute_roundtrip")
	                   }, {
	                           field : "roundTrip3",
	                           title : translate("trouble_shoot_traceroute_roundtrip")
	                   }]
	           };
	        },50) 
       } 
       }  
       
  //Start Diagnostic code       
       
       //load list of tests
		$scope.diagnosticTestSource=[];
		$scope.loadTestsList = function(){	        
	        var diagnosticTestSource = {
				"testText": translate("trouble_shoot_diagnostic_alltests"), 
   				"testValue":"all"
   		    };
   		    $scope.diagnosticTestSource.push(diagnosticTestSource); 
	       	var diagnosticTestSource1 ={
	        	"testText": translate("trouble_shoot_diagnostic_basictests"),  				
		        "testValue":"basic"	        	     			
	        }; 
   		  	$scope.diagnosticTestSource.push(diagnosticTestSource1); 
   		     if($rootScope.deviceInfo.type.indexOf("2960X")!=-1 || $rootScope.deviceInfo.type.indexOf("3560CX")!=-1 || $rootScope.deviceInfo.type.indexOf("2960XR")!=-1 || $rootScope.deviceInfo.type.indexOf("2960C")!=-1 || $rootScope.deviceInfo.type.indexOf("WS-C2960+")!=-1 ){
	       	  var diagnosticTestSource2 ={
	        	"testText": translate("trouble_shoot_diagnostic_nondisruptive"),  				
		        "testValue":"non-disruptive"	        	     			
	          }; 
		  	  $scope.diagnosticTestSource.push(diagnosticTestSource2); 
   		    }	
	    }
	    $scope.loadTestsList();
	    
	    $scope.startDiagnostic = function(evt) {
			$scope.startConfirmation('start');
		};
		$scope.startConfirmation = function() {
			$scope.tsTest = dialogService.dialog({
				content : translate("trouble_shoot_diagnostic_confirm"),
				title : translate("msg_delete_confirmation_window"),
				messageType : "confirm",
				actionButtons : [{
					text : translate("com_ok"),
					callback : "callDiagnosticTest"
				}, {
					text : translate("com_cancel")
				}]
			});
		};
		$scope.$on("callDiagnosticTest", function(event, data) {
			$scope.startTests($scope.tsTest.data("kendoWindow"));
		});
		 $scope.startTests= function(popup) {
		    	popup.close();			    	
		    	var formToSubmit = document.getElementById("diagnosticForm");
		    	 if(($rootScope.deviceInfo.type.indexOf("2960X")!=-1 && ($rootScope.deviceInfo.type != "WS-C2960X-24PSQ-L" &&
                                                $rootScope.deviceInfo.type != "WS-C2960X-48TS-LL" &&
                                                $rootScope.deviceInfo.type != "WS-C2960X-24TS-LL" ))
					|| $rootScope.deviceInfo.type.indexOf("2960XR")!=-1
					|| $rootScope.deviceInfo.type == "WS-C3560CX-12PD-S" || $rootScope.deviceInfo.type == "WS-C3560CX-8XPD-S" ){
		    		
		    		 if($scope.diagnosticTest==="basic"){
		       		        formToSubmit.action = "/level/15/exec/-/diagnostic/start/switch/"+$rootScope.deviceInfo.masterId+"/test/basic";	
			    		 } else if($scope.diagnosticTest==="all"){
			    			 formToSubmit.action = "/level/15/exec/-/diagnostic/start/switch/"+$rootScope.deviceInfo.masterId+"/test/all";	
			    		 } else{
			    			 formToSubmit.action = "/level/15/exec/-/diagnostic/start/switch/"+$rootScope.deviceInfo.masterId+"/test/non-disruptive";		
			    		 }
		    	 }else{
		    		 if($scope.diagnosticTest==="basic"){
		    		      formToSubmit.action = "/level/15/exec/-/diagnostic/start/test/basic";	
		    		 } else if($scope.diagnosticTest==="all"){		    			
		    		      formToSubmit.action = "/level/15/exec/-/diagnostic/start/test/all";		    		    
		    		 } else{		    		
		    			  formToSubmit.action = "/level/15/exec/-/diagnostic/start/test/non-disruptive";	
		    		 }
		    	 }	
		    	formToSubmit.submit();	
		    	$scope.diagnosticResults();
		 }   	
	    $scope.diagnosticResults= function() {	
	    	 var showDiagnosticResult ="";	  
	    	 if(($rootScope.deviceInfo.type.indexOf("2960X") !=-1 && ($rootScope.deviceInfo.type != "WS-C2960X-24PSQ-L" && 
                                                $rootScope.deviceInfo.type != "WS-C2960X-48TS-LL" &&
                                                $rootScope.deviceInfo.type != "WS-C2960X-24TS-LL" )) || $rootScope.deviceInfo.type.indexOf("2960XR")!=-1
				|| $rootScope.deviceInfo.type === "WS-C3560CX-12PD-S" || $rootScope.deviceInfo.type === "WS-C3560CX-8XPD-S" )
	    	 {
	    		 showDiagnosticResult=deviceCommunicator.getExecCmdOutput("show diagnostic result switch "+$rootScope.deviceInfo.masterId+" \n"); 
	    	 }else{
	    		 showDiagnosticResult=deviceCommunicator.getExecCmdOutput("show diagnostic result \n");
	    	 }	
	    	 var DIAGNOSTIC_TEST1 = new Array("TestPortAsicStackPortLoopback");
	    	 var DIAGNOSTIC_TEST2 = new Array("TestPortAsicLoopback");
	    	 var DIAGNOSTIC_TEST3 = new Array("TestPortAsicRingLoopback");
	    	 var DIAGNOSTIC_TEST4 = new Array("TestPortAsicCam");
	    	 var DIAGNOSTIC_TEST5 = new Array("TestMicRingLoopback");
	    	 var DIAGNOSTIC_TEST6 = new Array("TestPortAsicMem");
	    	 var DIAGNOSTIC_TEST7 = new Array("TestInlinePwrCtlr");
	    	 
	    	if(showDiagnosticResult!=null){	    		
	    		if($rootScope.deviceInfo.type.indexOf("2960X")!=-1 || $rootScope.deviceInfo.type.indexOf("2960XR")!=-1 || $rootScope.deviceInfo.type.indexOf("3560CX")!=-1 || $rootScope.deviceInfo.type.indexOf("2960C")!=-1 || $rootScope.deviceInfo.type.indexOf("WS-C2960+")!=-1){
	    			
		    		var testPortAsicStackPortLoopback = getStringLineService.getLines(showDiagnosticResult,DIAGNOSTIC_TEST1);
		    		if(testPortAsicStackPortLoopback!=undefined && testPortAsicStackPortLoopback.length>0 ){
		    			$scope.testView1=true;
			    		var arrtestPortAsicStackPortLoopback=testPortAsicStackPortLoopback[0].split(" ");
			    		testPortAsicStackPortLoopback=arrtestPortAsicStackPortLoopback[7].trim();
			    		if(testPortAsicStackPortLoopback==="U"){
			    			$scope.testResult1="fa fa-ban";
			    		}else if(testPortAsicStackPortLoopback==="F"){
			    			$scope.testResult1="fa fa-times-circle redCross";
			    		} else if(testPortAsicStackPortLoopback==="."){
			    			$scope.testResult1="fa fa-check-circle master";
			    		}
		    		}else{
	    				$scope.testView1=false;
	    			}		    		
		    		
			    	var testPortAsicRingLoopback = getStringLineService.getLines(showDiagnosticResult,DIAGNOSTIC_TEST3);
			    	if(testPortAsicRingLoopback!=undefined && testPortAsicRingLoopback.length>0 ){
			    		$scope.testView3=true;
			    		var arrtestPortAsicRingLoopback=testPortAsicRingLoopback[0].split(" ");
			    		testPortAsicRingLoopback=arrtestPortAsicRingLoopback[7].trim();
			    		if(testPortAsicRingLoopback==="U"){
			    			$scope.testResult3="fa fa-ban";
			    		}else if(testPortAsicRingLoopback==="F"){
			    			$scope.testResult3="fa fa-times-circle redCross";
			    		} else if(testPortAsicRingLoopback==="."){
			    			$scope.testResult3="fa fa-check-circle master";
			    		}
		    		}else{
	    				$scope.testView3=false;
	    			}
		    		
		    		var testMicRingLoopback = getStringLineService.getLines(showDiagnosticResult,DIAGNOSTIC_TEST5);
		    		if(testMicRingLoopback!=undefined && testMicRingLoopback.length>0 ){
		    			$scope.testView5=true;
			    		var arrtestMicRingLoopback=testMicRingLoopback[0].split(" ");
			    		testMicRingLoopback=arrtestMicRingLoopback[7].trim();
			    		if(testMicRingLoopback==="U"){
			    			$scope.testResult5="fa fa-ban";
			    		}else if(testMicRingLoopback==="F"){
			    			$scope.testResult5="fa fa-times-circle redCross";
			    		} else if(testMicRingLoopback==="."){
			    			$scope.testResult5="fa fa-check-circle master";
			    		}
		    		}else{
	    				$scope.testView5=false;
	    			}
	    		}
	    		
	    		var testPortAsicLoopback = getStringLineService.getLines(showDiagnosticResult,DIAGNOSTIC_TEST2);
	    		if(testPortAsicLoopback!=undefined && testPortAsicLoopback.length>0 ){
	    			$scope.testView2=true;
		    		var arrtestPortAsicLoopback=testPortAsicLoopback[0].split(" ");
		    		testPortAsicLoopback=arrtestPortAsicLoopback[7].trim();
		    		if(testPortAsicLoopback==="U"){
		    			$scope.testResult2="fa fa-ban";
		    		}else if(testPortAsicLoopback==="F"){
		    			$scope.testResult2="fa fa-times-circle redCross";
		    		} else if(testPortAsicLoopback==="."){
		    			$scope.testResult2="fa fa-check-circle master";
		    		}
	    		}else{
    				$scope.testView2=false;
    			}	    		
	    		
	    		var testPortAsicCam = getStringLineService.getLines(showDiagnosticResult,DIAGNOSTIC_TEST4);
	    		if(testPortAsicCam!=undefined && testPortAsicCam.length>0 ){
	    			$scope.testView4=true;
		    		var arrtestPortAsicCam=testPortAsicCam[0].split(" ");
		    		testPortAsicCam=arrtestPortAsicCam[7].trim();
		    		if(testPortAsicCam==="U"){
		    			$scope.testResult4="fa fa-ban";
		    		}else if(testPortAsicCam==="F"){
		    			$scope.testResult4="fa fa-times-circle redCross";
		    		} else if(testPortAsicCam==="."){
		    			$scope.testResult4="fa fa-check-circle master";
		    		}	  
	    		}else{
    				$scope.testView4=false;
    			}	    		
	    		
	    		var testPortAsicMem = getStringLineService.getLines(showDiagnosticResult,DIAGNOSTIC_TEST6);
	    		if(testPortAsicMem!=undefined && testPortAsicMem.length>0 ){
	    			$scope.testView6=true;
		    		var arrtestPortAsicMem=testPortAsicMem[0].split(" ");
		    		testPortAsicMem=arrtestPortAsicMem[7].trim();
		    		if(testPortAsicMem==="U"){
		    			$scope.testResult6="fa fa-ban";
		    		}else if(testPortAsicMem==="F"){
		    			$scope.testResult6="fa fa-times-circle redCross";
		    		} else if(testPortAsicMem==="."){
		    			$scope.testResult6="fa fa-check-circle master";
		    		}
	    		}else{
    				$scope.testView6=false;
    			}
	    		
	    		if($rootScope.deviceInfo.type.indexOf("2960X")!=-1 || $rootScope.deviceInfo.type.indexOf("2960XR")!=-1 || $rootScope.deviceInfo.type.indexOf("2960CX")!=-1 || $rootScope.deviceInfo.type === "WS-C3560CX-12PD-S" || $rootScope.deviceInfo.type === "WS-C3560CX-8XPD-S"){
	    			var testInlinePwrCtlr = getStringLineService.getLines(showDiagnosticResult,DIAGNOSTIC_TEST7);
	    			if(testInlinePwrCtlr!=undefined && testInlinePwrCtlr.length>0 ){
	    				$scope.testView7=true;
			    		var arrtestInlinePwrCtlr=testInlinePwrCtlr[0].split(" ");
			    		testInlinePwrCtlr=arrtestInlinePwrCtlr[7].trim();
			    		if(testInlinePwrCtlr==="U"){
			    			$scope.testResult7="fa fa-ban";
			    		}else if(testInlinePwrCtlr==="F"){
			    			$scope.testResult7="fa fa-times-circle redCross";
			    		} else if(testInlinePwrCtlr==="."){
			    			$scope.testResult7="fa fa-check-circle master";
			    		}
	    			}else{
	    				$scope.testView7=false;
	    			}	
	    		}
	    		
	    	}	    	
	    } 
	    
	    $scope.diagnosticResults();
	  	    
		
	}]);
