/**
 Description: Services for STP.
 Copyright (c) 2016 by Cisco Systems, Inc.
 All rights reserved.
 */
app.service('stpdataSourceService',['$rootScope','requestRoutingService','getStringLineService','executeCliCmdService','$filter', function($rootScope,requestRoutingService,getStringLineService,executeCliCmdService,$filter) {
	var trimVal=$filter('trimValue');
	var translate = $filter("translate");
  var versionInfo = requestRoutingService.getShowCmdOutput("show version","overviewshVer");
  var deviceType = versionInfo.ShowVersion.name;
	var vlanIdManipulation=function(vlanId,enumeration){
        var my_string = '' + vlanId;
        while (my_string.length < enumeration) {
            my_string = '0' + my_string;
        }
        return my_string;
    };

    var getBridgePriority=function(vlanId){

        var cmdString = "show spanning-tree vlan ";
        cmdString = cmdString + vlanId;
        var bridgePriorityNumber = requestRoutingService.getShowCmdOutput(cmdString, "showSpanningtreeVlan");
        return bridgePriorityNumber.showSpanningTreeVlan.wnwebdata.VLAN.BridgeID.priority;
    };
    return{
        setHostName:function(hostName){
            var cliHostNameCmd="hostname ";
            cliHostNameCmd=cliHostNameCmd+hostName;
            var resultResponse=requestRoutingService.getConfigCmdOutput(cliHostNameCmd);

        },
        setIpAddress:function(ipAddress,subnetMask){
            var cliCommand="ip address ";
            cliCommand=cliCommand+ipAddress+" "+subnetMask;
            var resultResponse=requestRoutingService.getConfigCmdOutput(cliCommand);
        },
        setMtuSize:function(mtuSize){
          var cliCommand="system mtu ";
            cliCommand=cliCommand+mtuSize;
            var resultResponse=requestRoutingService.getConfigCmdOutput(cliCommand);
        },
        sendingStpModeToDevice : function(stpModeType){
            var stpCliCommand="spanning-tree mode ";
            var stpValue=stpModeType;
            stpCliCommand=stpCliCommand+stpValue;
            var resultResponse=requestRoutingService.getConfigCmdOutput(stpCliCommand);
        },
        sendingVlanDataToDevice:function(editedObject){        	
            var vlanCliCommand = "";
            editedObject.forEach(function(changedTableItem){
                   if(changedTableItem.hasSpanningTree === false){
                        vlanCliCommand+="no spanning-tree vlan "+changedTableItem.vlanId+" \n";
                   }else{
                	   vlanCliCommand+="spanning-tree vlan "+changedTableItem.vlanId+"\n";
                       vlanCliCommand+="spanning-tree vlan "+changedTableItem.vlanId+" priority "+changedTableItem.bridgePriorityNumber+"\n";
                   }                  
            });
            var resultResponse=requestRoutingService.getConfigCmdOutput(vlanCliCommand);
            return resultResponse;

        },
        getStpModeType:function(){
            var responseStpModeType=requestRoutingService.getShowCmdOutput("show spanning-tree summary","showMode");
            return responseStpModeType.ShowSTP.modeType;
        },
        getVlanData:function(){
        	var arrSTP=new Array();            
            var responsevlanBriefData= requestRoutingService.getShowCmdOutput("show vlan brief","showVlanBrief");
            var vlanBriefData=responsevlanBriefData.ShowVlanBrief.VlanBriefTable.entry;
             
            var OUTPUT_BEGIN = new Array("spanning-tree vlan "); 
            var OUTPUT_END = new Array("\n");
            var arrVlanId=new Array();
            var arrPriority=new Array();
            var arrVlanId1=new Array();
            var arrPriority1=new Array();
            
            var strCLIOutput = deviceCommunicator.getExecCmdOutput("sh run | s spanning-tree");
            var strLines = getStringLineService.getLines(strCLIOutput,OUTPUT_BEGIN);
            if (strLines != null) {
                for (var i=0; i<strLines.length; i++) {
                       var strLine = strLines[i]; 
                       if(strLine.indexOf("no spanning-tree vlan")!=-1){  //for disabled state vlan's                   	   
                    	 vlanList= executeCliCmdService.getNextString(strLine,OUTPUT_BEGIN,OUTPUT_END);
                      	 arrValList=vlanList.split(" ");
                         if(vlanList.indexOf(",")!=-1){
                        		 vlansList=arrValList[0];
                        		 arrVlansList=vlansList.split(",");
                        		 for (var j=0; j<arrVlansList.length; j++) {
                        			if(arrVlansList[j].indexOf("-")!=-1){
                        				vlanMultiList=arrVlansList[j].split("-");
                        				for (var k=vlanMultiList[0]; k<= vlanMultiList[1]; k++) {
                        					arrVlanId1.push(k);
                        				}                          				
                        			}else{
                        				arrVlanId1.push(arrVlansList[j]);
                               		}
                        		 }                         		 
                          	 
                           }else{ 
                          	 if(vlanList.indexOf("-")!=-1){                            		
                     				vlanMultiList=arrValList[0].split("-");
                     				for (var k=vlanMultiList[0]; k<= vlanMultiList[1]; k++) {
                     					arrVlanId1.push(k);
                                	}                       				
                     			}else{                     				
                     				arrVlanId1.push(arrValList[0]);
                     			}
                         }                    	   
                       }else{ //for enabled state vlan's 
                             vlanList= executeCliCmdService.getNextString(strLine,OUTPUT_BEGIN,OUTPUT_END);
                        	 arrValList=vlanList.split(" ");
                             if(vlanList.indexOf(",")!=-1){
                          		 vlansList=arrValList[0];
                          		 arrVlansList=vlansList.split(",");
                          		 for (var j=0; j<arrVlansList.length; j++) {
                          			if(arrVlansList[j].indexOf("-")!=-1){
                          				vlanMultiList=arrVlansList[j].split("-");
                          				for (var k=vlanMultiList[0]; k<= vlanMultiList[1]; k++) {
                          					arrVlanId.push(k);
                                     		arrPriority.push(arrValList[2]);
                          				}                          				
                          			}else{
                          				arrVlanId.push(arrVlansList[j]);
                                 		arrPriority.push(arrValList[2]);
                          			}
                          		 }                            	 
                             }else{ 
                            	 if(vlanList.indexOf("-")!=-1){                            		
                       				vlanMultiList=arrValList[0].split("-");
                       				for (var k=vlanMultiList[0]; k<= vlanMultiList[1]; k++) {
                       					arrVlanId.push(k);
                                  		arrPriority.push(arrValList[2]);
                       				}                       				
                       			}else{                       				
                       				arrVlanId.push(arrValList[0]);
                       				arrPriority.push(arrValList[2]);
                       			}
                           }
                     }       
                }
            }    
            
            for(var item=0;item < vlanBriefData.length;item++){
            	if (vlanBriefData[item].name != "" &&  vlanBriefData[item].name != "token-ring-default" && vlanBriefData[item].name != "MGMT_VLAN" && vlanBriefData[item].name != "DataVlan" && vlanBriefData[item].name != "VoiceVlan" && vlanBriefData[item].name != "fddi-default" && vlanBriefData[item].name != "trnet-default" && vlanBriefData[item].name != "fddinet-default") {
                	var stpObj = {};
                	var count=0;
                	
                	stpObj["vlanId"] = vlanBriefData[item].vlan;
                    stpObj["vlanName"] = vlanBriefData[item].name == "default" ? translate("port_config_default") : vlanBriefData[item].name;  
                    stpObj["bridgePriorityNumber"] = "32768"; //set default bridge priority
                    stpObj["hasSpanningTree"] = true; //set default ST status
                    
                    for(var i=0;i <arrVlanId.length;i++){
                    	if(vlanBriefData[item].vlan==arrVlanId[i]){                    		
                    		stpObj["bridgePriorityNumber"] = arrPriority[i]; 
                            stpObj["hasSpanningTree"] = true; 
                            count++;
                    	}                    		
                    } 
                    
                    for(var j=0;j <arrVlanId1.length;j++){
                    	if(vlanBriefData[item].vlan==arrVlanId1[j]){   
                    		if(count==0){
                    			stpObj["bridgePriorityNumber"] = "32768"; 
                    		}                    		
                            stpObj["hasSpanningTree"] = false;                           
                    	}                    		
                    } 
                    
                    arrSTP.push(stpObj);
               }
           }
                return arrSTP;
        },
        getSwitchNames: function(){
          var switchName = deviceCommunicator.getExecCmdOutput("show switch");
          return "aaa";
        },
        getShowCluster: function(){
          var showCluster=requestRoutingService.getShowCmdOutput("show cluster", "showCluster");
          return showCluster;
        },
        getShowClusterMembers: function(){
          var showClusterMember=requestRoutingService.getShowCmdOutput("show cluster member", "showClusterMembers");
          return showClusterMember;
        },
        getShowClusterCandidates: function(){
          var showClusterCandidates=requestRoutingService.getShowCmdOutput("show cluster candidates", "showClusterCandidates");
          return showClusterCandidates;
        },
        getSwitchDetails:function(){
            var switchData={};
            var switchResponse=requestRoutingService.getShowCmdOutput("show version","overviewshVer");
            switchData["hostName"]=switchResponse.ShowVersion.hostname;
            
            var switchDetailResponse=requestRoutingService.getShowCmdOutput("show ip interface","switchIpInterface");
            switchDetailResponse = (switchDetailResponse && switchDetailResponse.ShowInterface.wnwebdata.entry) ? switchDetailResponse.ShowInterface.wnwebdata.entry : [];
            var httpIpAddress = deviceCommunicator.getExecCmdOutput("show ip http server history | i [0-9]+");
            httpIpAddressList=httpIpAddress.split("\n");
            arrayLength=httpIpAddressList.length;
                        
            arrHttpIpAddress=trimVal(httpIpAddressList[arrayLength-1]).split(" ");
            mgmtIpaddress=arrHttpIpAddress[0].split(":");
            var currentIpAdddress=mgmtIpaddress[0];
            currentIpAdddress=trimVal(currentIpAdddress)
                                
            var vlan="";
            var ipAddress="";
            if (switchDetailResponse.length > 0) {
                for (var i = 0; i < switchDetailResponse.length; i++) {
                	vlan= switchDetailResponse[i].Vlan;
                	ipAddress= switchDetailResponse[i].ipAddress;  
                	if(ipAddress!=undefined){
                		aripAddress=ipAddress.split("/");
                		newIP=trimVal(aripAddress[0]);
                		if(newIP==currentIpAdddress){
                			switchData["managementVlan"]=vlan;
                			break;
                		}
                	}
                }
            }else if (switchDetailResponse.Vlan) {
            	   vlan= switchDetailResponse.Vlan;
            	   ipAddress= switchDetailResponse.ipAddress;
            	   if(ipAddress!=undefined){
               		aripAddress=ipAddress.split("/");
               		newIP=trimVal(aripAddress[0]);
               		if(newIP==currentIpAdddress){
               			switchData["managementVlan"]=vlan;
               		}
               	}
            }
            
            var switchShowRun=requestRoutingService.getShowCmdOutput("show running-config","showRun");
            switchData["defaultGateway"]=switchShowRun.ShowRun.wnwebdata.defaultGateway;            
                       
            var switchShowRunIPAddress=requestRoutingService.getShowCmdOutput("show running-config int "+switchData["managementVlan"]+"","showRunIpAddress");
            var switchIPAddress=switchShowRunIPAddress.ShowRun.wnwebdata.ipAddress;
            arrSwitchIPAddress=switchIPAddress.split(" ");
            switchData["switchIp"]=arrSwitchIPAddress[0]
            switchData["subnetMask"]=arrSwitchIPAddress[1];
            
            var strCLIOutputMTU = deviceCommunicator.getExecCmdOutput("show system mtu");
            var START_INPUT= new Array("System MTU size is ");
    		var END_INPUT= new Array(" bytes");
    		var MTUValue= executeCliCmdService.getNextString(strCLIOutputMTU,START_INPUT,END_INPUT);
    		switchData["mtuSize"]=trimVal(MTUValue);
    		
    		//Adding selecon support
            if(deviceType.indexOf("CDB")!=-1){
	    		var coapStatus = deviceCommunicator.getExecCmdOutput("show coap stats");
	    		if(coapStatus.indexOf("COAP is disabled")!=-1){
	    			switchData["switchCOAP"]=false;
	    		}else{
	    			switchData["switchCOAP"]=true;
	    		}
            }
            
            return switchData;
        }
     
    }
}]);
