/**
 Description: Controller for Trouble Shooting
 Copyright (c) 2016 by Cisco Systems, Inc.
 All rights reserved.
 */
app.controller('netFlowCtrl', ['$scope','$rootScope','$timeout', '$filter', 'gridCrudService','requestRoutingService','dataSourceService','dialogService','notificationService','executeCliCmdService','validationService','getStringLineService',
	function($scope,$rootScope,$timeout, $filter, gridCrudService,requestRoutingService,dataSourceService,dialogService,notificationService,executeCliCmdService,validationService,getStringLineService) {
		var trimVal=$filter('trimValue');
		var translate = $filter("translate");
		var versionInfo = requestRoutingService.getShowCmdOutput("show version","overviewshVer");
        var deviceType = versionInfo.ShowVersion.name;
        var samplerTotalLimit = 4;
		// $scope Variables are declared using angular.extend method. 
		angular.extend($scope, {
			netFlowTemplateDataSource: [{nftText: translate("nft_application"), nftValue:'defaultApplicationTraffic', nftShort:'dat'},
                        {nftText: translate("nft_serverUtil"), nftValue:'defaultServerUtilization', nftShort:'dsu'},
                        {nftText: translate("nft_security"), nftValue:'defaultSecurity', nftShort:'ds'},
                        {nftText: translate("nft_capacityPlan"), nftValue:'defaultCapacityPlanning', nftShort:'dcp'},
                        {nftText: translate("nft_stealthWatch"), nftValue:'defaultStealthWatch', nftShort:'dsw'}],

            samplingMethodDataSource: [{samplingMethodText: translate("nf_sampling_deterministic"), samplingMethodValue:'deterministic'},
                        {samplingMethodText: translate("nf_sampling_random"), samplingMethodValue:'random'}],
            netFlowTemplateType: '',
            switchExportAddType: '',
            samplingMethodType: '',
            inputCapIntType: '',
            samplingMethodRangeType: '',
            collectorIpAddress: '',
            switchExportAddress: [],
            inputCaptureInterface: [],
            samplerMethodRange: [],
            selectedNetFlowMonitorsArray: [],
            monitorUnitName: 'dM',
            countNetFlow: 0,
            diableCreateButton: true,
            diableCancelButton: true,
            enableDeleteBtn: true,
            fullNetFlowSupport:false
		});

		// Find the current Device
		if(deviceType.indexOf("2960X") != -1 || deviceType.indexOf("2960XR") != -1){
			var fullNetFlow = {samplingMethodText: translate("nf_sampling_fullnetflow"), samplingMethodValue:'fullnetflow'};
			$scope.samplingMethodDataSource.push(fullNetFlow);
			$scope.fullNetFlowSupport = true;
		}
		//validation
        var netFlowFormValidations = angular.element("#netFlowForm").kendoValidator({
            rules: {
                validateip: function (input) {
                    return validationService.validateIPAddress(input);
                },
                dataspace: function (input) {
                    return validationService.validateDataSpace(input);
                },
                check: function (input) {
                    var valMsg = input.data('checkMsg');
                        if ((valMsg==undefined)) {
                            return true;
                        }
                    return validationService.validateCheck(input);
                },
				range: function (input) {
					if(input.val()){
						if(input.val() != ""){
							var count=0;
							var valMsg = input.data('rangeMsg');
							if ((valMsg==undefined)) {
								return true;
							}
							var min= trimVal(input.prop('min'));
							var max= trimVal(input.prop('max'));
							var arr = input.val().replace('-',',');
							arr= arr.split(',');						
							for(var i=0;i<arr.length;i++){
								if(parseFloat(trimVal(arr[i]))>=min && parseFloat(trimVal(arr[i]))<=max) {
									count++;
								}
							}
							if(arr.length!=count){
								return false;
							}
							return true;
						}
						else return true;
					}else{
						return true;
					}
				}
            }
        }).data("kendoValidator");

        // The Function to convert Ip Address to Hex Values.
        $scope.convertIpAddressToHex = function(ipAddress){
        	ipAddress = ipAddress.toString();
        	var splitDotFromIpAdd = ipAddress.split('.'), result = "";
        	for(var i = 0; i < splitDotFromIpAdd.length; i++){
        		if(Number(splitDotFromIpAdd[i]) < 15){
        			result += "0";	
        		}
        			result += parseInt(splitDotFromIpAdd[i]).toString(16);
        	}
        	return result;
        }
        $scope.netFlowMonitorsGridOptions = {
            filterable: true,
            sortable: 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")
				},
				refresh: false,
                pageSizes: gridCrudService.grid_page_sizes, // This page size variable is written in datasourceService.js file.
                buttonCount: 4
            },
            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")
		        }
			},
			scrollable:false,
            selectable: true,
            columns: [
                {
                    "template": "<input type=\"checkbox\"  ng-model=\"checkedNFMonitor\" ng-click=\"isChecked(checkedNFMonitor,dataItem,'Community')\"  />",
                    sortable: false,
                    width: 40
                },
                {
                    field: "SamplerInterFaces",
                    sortable: false,
		            title: translate("nf_interface")
                },
                {
                    field: "NetflowTemplate",
                    title : translate("nf_template")
                },
                {
                    field: "Collector",
                    title : translate("nf_collector")
                },
                {
                    field: "Switch",
                    title : translate("nf_switch")
                },
                {
                    field: "samplingField",
                    title : translate("nf_sampling")
                }
            ]
        };
        $scope.loadGridData = function () {
	        $scope.netFlowMonitorsGridData = new kendo.data.ObservableArray([]);
	        //show flow monitor
	        var samplingStrCLIOutput="", showFlowInterface = "";
	        var strCLIOutput = deviceCommunicator.getExecCmdOutput("show flow monitor");
	        var START_FLOW_MONITOR = ["Flow Monitor "];
	        var START_FLOW_RECORD = ["Flow Record:"];
            var START_FLOW_EXPORTER = ["Flow Exporter:"];
	        var END_FLOW_MONITOR = [":"];
	        var END_OUTPUT = ["\n"];
	        var arrFlowMonitor=strCLIOutput.split("Flow Monitor");
            samplingStrCLIOutput = deviceCommunicator.getExecCmdOutput("show sampler\n");
            showFlowInterface = deviceCommunicator.getExecCmdOutput("show flow interface\n");
            var showFlowIntSamplers = getStringLineService.getLines(showFlowInterface,['traffic(ip): ']);
	    var ipv6Samplers = getStringLineService.getLines(showFlowInterface,['traffic(ipv6): ']);
            showFlowIntSamplers = showFlowIntSamplers.concat(ipv6Samplers);
            var showFlowIntMonitors = getStringLineService.getLines(showFlowInterface,['monitor: ']);
	        var LINE_INDEX = ["flow monitor"];
            var samplingNameStrLines = getStringLineService.getLines(samplingStrCLIOutput,['Sampler ']);
	        var samplingTypeStrLines = getStringLineService.getLines(samplingStrCLIOutput,['Type: ']);
            var netFlowMonitorObj = {};
            var sampler = [];
            var showRunConfigInterface = [];
            $scope.showFlowIntRecords = [];
            //Associated Interface values
            var intStrCLIOutput = deviceCommunicator.getExecCmdOutput("show running-config | section interface");
            var showRunConfigSecInterface = intStrCLIOutput.split("interface ");
            var showRunConfigSecInterfaceRecord;
            var START_FLOW_IPFLOW = ["monitor "];
            var END_FLOW_INTERFACE = [" input"];
            
            for(var inter = 1; inter < showRunConfigSecInterface.length; inter++){
                if(showRunConfigSecInterface[inter].indexOf("ip flow monitor")!=-1){
                    var interfaceAssociateMonitorSampler = showRunConfigSecInterface[inter].split("ip flow ");
                    showRunConfigInterface.push(showRunConfigSecInterface[inter]);
                } else if(showRunConfigSecInterface[inter].indexOf("ipv6 flow monitor")!=-1){
                    var interfaceAssociateMonitorSampler = showRunConfigSecInterface[inter].split("ipv6 flow ");
                    showRunConfigInterface.push(showRunConfigSecInterface[inter]);
                }
            }
            //Associated Interface values Ends
            for (var i = 1; i < arrFlowMonitor.length; i++) {
	         	var flowMonitor=arrFlowMonitor[i];
	         	flowMonitor="Flow Monitor "+flowMonitor;
	         	var flowMonitorName = executeCliCmdService.getNextString(flowMonitor,START_FLOW_MONITOR,END_FLOW_MONITOR);
	         		flowMonitorName = flowMonitorName.trim();
	         	var flowRecord = executeCliCmdService.getNextString(flowMonitor,START_FLOW_RECORD,END_OUTPUT);
	         		flowRecord = flowRecord.trim();
                var flowExporter = executeCliCmdService.getNextString(flowMonitor,START_FLOW_EXPORTER,END_OUTPUT);	
                if(flowExporter !== ""){
                    var flowExporterValue = flowExporter.trim().replace(/ *\([^)]*\) */g, "");
                    var tempSamplerName = flowMonitorName.substring($scope.monitorUnitName.length);
                    
                    for(var shwInt = 0; shwInt < showFlowIntSamplers.length; shwInt++){
			var showFlowIntSamplerNames = "";
                    	if(showFlowIntSamplers[shwInt].indexOf("traffic(ipv6):") != -1){
                    		showFlowIntSamplerNames = showFlowIntSamplers[shwInt].split("traffic(ipv6):")[1].trim();
                    	} else {
                    		showFlowIntSamplerNames = showFlowIntSamplers[shwInt].split("traffic(ip):")[1].trim();
                    	}
                        var showFlowIntMonitorNames = showFlowIntMonitors[shwInt].split("FNF:  monitor: ")[1].trim();
                        if(showFlowIntMonitorNames === flowMonitorName){
                            if(showFlowIntSamplerNames.indexOf("sampler ")!=-1){
                                var allSamplerNames = showFlowIntSamplerNames.split("sampler")[1].trim();
                                var showSampler = requestRoutingService.getShowCmdOutput("show sampler "+allSamplerNames, "showSampler");
                                netFlowMonitorObj.Sampling = showSampler.showsampler.samplerType;
                                netFlowMonitorObj.samplingField = $filter('filter')($scope.samplingMethodDataSource, {"samplingMethodValue":netFlowMonitorObj.Sampling})[0].samplingMethodText;
                                netFlowMonitorObj.SamplerName = allSamplerNames;
                            }else{
                                netFlowMonitorObj.Sampling = "fullnetflow";
                                netFlowMonitorObj.samplingField = $filter('filter')($scope.samplingMethodDataSource, {"samplingMethodValue":netFlowMonitorObj.Sampling})[0].samplingMethodText;
                                netFlowMonitorObj.SamplerName = "";
                            }
                        }
                    }
             		var netFlowTemplateTemp = $filter('filter')($scope.netFlowTemplateDataSource, {"nftValue":flowRecord})
             			,showFlowExporter = requestRoutingService.getShowCmdOutput("show flow exporter "+flowExporterValue, "showFlowExporter")
            			,shortNameOfNFTemplate = $filter('filter')($scope.netFlowTemplateDataSource, {"nftValue":flowRecord});
                		
                    if(showFlowExporter.showexporter.collectorIpAddress){
                        netFlowMonitorObj.Collector = showFlowExporter.showexporter.collectorIpAddress;
                    }
        			netFlowMonitorObj.NetflowTemplate =  netFlowTemplateTemp[0].nftText;
	        		netFlowMonitorObj.FlowRecord = flowRecord;
	        		netFlowMonitorObj.FlowExporter = flowExporterValue;
	        		netFlowMonitorObj.FlowMonitorName = flowMonitorName;
	        		netFlowMonitorObj.Interface = showFlowExporter.showexporter.interface;
	        		netFlowMonitorObj.Switch = showFlowExporter.showexporter.switchIpAddress;
	        		if(showRunConfigInterface.length > 0){
                        for(var inter = 0; inter < showRunConfigInterface.length; inter++){
                            if(showRunConfigInterface[inter].indexOf(netFlowMonitorObj.FlowMonitorName) !== -1){
				var interfaceMonSampIntName = "";
                                if(showRunConfigInterface[inter].indexOf("ip flow monitor") != -1){
                                	interfaceMonSampIntName = showRunConfigInterface[inter].split("ip flow monitor ");
                                } else {
                                 	interfaceMonSampIntName = showRunConfigInterface[inter].split("ipv6 flow monitor ");
                                }
                                var intNames = interfaceMonSampIntName[0].trim();
                                var intExtraHasNames = intNames.split(" ");
                                if(intExtraHasNames.length > 0){
                                    intNames = intExtraHasNames[0];
                                }
                                netFlowMonitorObj.SamplerInterFaces = intNames;
                                break;
                            }else{
                                netFlowMonitorObj.SamplerInterFaces = "";
                            }
                        }
                        if(netFlowMonitorObj.SamplerInterFaces !== ""){
                            $scope.netFlowMonitorsGridData.push(netFlowMonitorObj);          
                        }
                    }
                }  
            }
	        $scope.netFlowMonitorsGridDataSource = new kendo.data.DataSource({
				pageSize: 10,
				data: $scope.netFlowMonitorsGridData
			});
        }
        $scope.isChecked = function (checked, dataItem) {
        	if (checked == false) {
                $scope.countNetFlow = $scope.countNetFlow - 1;
                var index = $scope.selectedNetFlowMonitorsArray.indexOf(dataItem);
                if (index > -1) {
                    $scope.selectedNetFlowMonitorsArray.splice(index, 1);
                }
            } else {
                $scope.countNetFlow = $scope.countNetFlow + 1;
                $scope.selectedNetFlowMonitorsArray.push(dataItem);
            }

            if ($scope.selectedNetFlowMonitorsArray.length > 0) {
                $scope.enableDeleteBtn = false;
            } else {
                $scope.enableDeleteBtn = true;
            }
        };
        $scope.rowSelected = function () {
        	$scope.enableDeleteBtn = false;
			$scope.disableApplyButton = true;
			if ($scope.netFlowMonitorsGridDataSource.hasChanges() === false) {
                $scope.disableApplyButton = false;
            } else if ($scope.netFlowMonitorsGridDataSource.hasChanges() === true) {
                $scope.disableApplyButton = false;
            }
        };
        $scope.deleteBtnFunction = function (popup) {
        	$scope.disableApplyButton = false;
            var netFlowConfigCLI = "";
            for (var monitorIndex = 0; monitorIndex < $scope.selectedNetFlowMonitorsArray.length; monitorIndex++) {
            	// Remove Associate Interface records.
		var ipType = ($scope.selectedNetFlowMonitorsArray[monitorIndex].NetflowTemplate == "Capacity Planning")?"no ipv6":"no ip";
                if($scope.selectedNetFlowMonitorsArray[monitorIndex].Sampling !== "fullnetflow"){
                    netFlowConfigCLI += "interface "+$scope.selectedNetFlowMonitorsArray[monitorIndex].SamplerInterFaces+"\n";
                	netFlowConfigCLI += ipType + " flow monitor "+$scope.selectedNetFlowMonitorsArray[monitorIndex].FlowMonitorName+" sampler "+$scope.selectedNetFlowMonitorsArray[monitorIndex].SamplerName+" input \n";
                    netFlowConfigCLI +=  "exit \n";
                }else{
                    netFlowConfigCLI += "interface "+$scope.selectedNetFlowMonitorsArray[monitorIndex].SamplerInterFaces+"\n";
                    netFlowConfigCLI += ipType + " flow monitor "+$scope.selectedNetFlowMonitorsArray[monitorIndex].FlowMonitorName+" input \n";
                    netFlowConfigCLI +=  "exit \n";
                }
                // Remove flow monitor records.
                netFlowConfigCLI += "no flow monitor "+$scope.selectedNetFlowMonitorsArray[monitorIndex].FlowMonitorName+" \n";
                $scope.netFlowMonitorsGrid.dataSource.remove($scope.selectedNetFlowMonitorsArray[monitorIndex]);
                // Remove sampler records.
                if($scope.selectedNetFlowMonitorsArray[monitorIndex].Sampling !== "fullnetflow"){
                    netFlowConfigCLI += "no sampler "+$scope.selectedNetFlowMonitorsArray[monitorIndex].SamplerName+" \n";
                }
                // Remove flow exporter records.
                netFlowConfigCLI += "no flow exporter "+$scope.selectedNetFlowMonitorsArray[monitorIndex].FlowExporter+" \n";
            }
            var result = requestRoutingService.getConfigCmdOutput(netFlowConfigCLI);
            if(result.hasOwnProperty('errorResponse')){
            	var exceptionalCase_1 = result.errorResponse.indexOf("Remove from all clients before deleting.");
            }
            if(result=="" || exceptionalCase_1 != -1){
            	notificationService.showNotification(translate('nf_delete_success_msg'),translate('com_config_success_title'),'success');
            }else{
            	notificationService.showNotification(result.errorResponse,translate('com_config_fail_title'),'error');
            }
            $scope.selectedNetFlowMonitorsArray = [];
            $scope.enableDeleteBtn = true;
            popup.close();
        };
        $scope.deleteConfirmation = function() {
			$scope.confirmationNetFlow('delete');
		};
        $scope.confirmationNetFlow = function() {
        	var interface=[];
        	angular.forEach($scope.selectedNetFlowMonitorsArray, function(val,indX){
        		interface.push(val.SamplerInterFaces);
        	});
			$scope.dlgNetFlow = dialogService.dialog({
				content : translate("nf_msg_delete_confirmation")+"<br/>"+interface,
				title : translate("msg_delete_confirmation_window"),
				messageType : "confirm",
				actionButtons : [{
					text : translate("com_ok"),
					callback : "netFlowDeleteConfirmation"
				}, {
					text : translate("com_cancel")
				}]
			});
		};
		$scope.$on("netFlowDeleteConfirmation", function(event, data) {
			$scope.deleteBtnFunction($scope.dlgNetFlow.data("kendoWindow"));
		});
        $scope.netFlowInit = function(){
        	var showInterfaces = requestRoutingService.getShowCmdOutput("show ip int brief", "showInterfaces");
        		showInterfaces = showInterfaces.showIpInterfaceBrief.IntBriefTable.entry;
                angular.forEach(showInterfaces, function(interface, index){
                    if(interface.interfaceName.indexOf("TenGigabitEthernet")!=-1){
                        interface.interfaceName = interface.interfaceName.replace("TenGigabitEthernet","Te");
                    }else if(interface.interfaceName.indexOf("FastEthernet")!=-1){
                        interface.interfaceName = interface.interfaceName.replace("FastEthernet","Fa");
                    }else if(interface.interfaceName.indexOf("GigabitEthernet")!=-1){
                        interface.interfaceName = interface.interfaceName.replace("GigabitEthernet","Gi");
                    }
                    if(interface.ipAddress != 'unassigned'){
        				var switchExportAddress = {
	        				"text": interface.interfaceName+"_"+interface.ipAddress,
	        				"ipAddress":interface.ipAddress,
	        				"name":interface.interfaceName
	        			};
                        $scope.switchExportAddress.push(switchExportAddress);        			
        			}
                    $scope.inputCaptureInterface.push(interface);
        		});
        		var min = 32, max = 1032; 
        	for (var i = min; i <= max; i++) {
        		$scope.samplerMethodRange.push(""+i);
		    }
		    $scope.loadGridData();	
        }
        //Initial load function for this controller 
        $scope.netFlowInit();

        $scope.fnCancel = function(){
            $scope.samplingMethodType = $scope.samplingMethodDataSource[0].samplingMethodValue;
            $scope.inputCapIntType = $scope.inputCaptureInterface[0].interfaceName;
            $scope.switchExportAddType = $scope.switchExportAddress[0].text;
            $scope.collectorIpAddress = "";
            angular.element("#samplerRangeContainer input").val("");
            $timeout(function(){
                netFlowFormValidations.hideMessages();//hiding the validator popup messges.
            },50)
        }
        $scope.manualGridRefresh = function(){
        	var grid = angular.element("#netFlowMonitorsGrid").data("kendoGrid");
            grid.dataSource = $scope.netFlowMonitorsGridDataSource;
            $scope.netFlowMonitorsGridDataSource.read();
            grid.refresh();
        }
        
        $scope.findCLICMDIsAlreadyExists = function(recordName, CLICommand){
            var recordCLI = deviceCommunicator.getExecCmdOutput(CLICommand);
            if(recordCLI.indexOf(recordName) !== -1){
                return true;
            }else{
                return false;
            }
        }

        $scope.findNetFlowTemplateIsAlreadyExists = function(netflowTemplate){
            var netflowTemplateRecord = deviceCommunicator.getExecCmdOutput("show flow record\n");
            if(netflowTemplateRecord.indexOf(netflowTemplate) !== -1){
                return true;
            }else{
                return false;
            }
        }
        // Create button event listener
        $scope.createNetFlow = function(){
            $scope.samplingMethodRangeType = angular.element("#samplerRangeContainer input").val();
            var flowRecordIsOneTime = $scope.findNetFlowTemplateIsAlreadyExists($scope.netFlowTemplateType);
            var showFlowExporter = deviceCommunicator.getExecCmdOutput("show running-config | section interface");
            var exporterIsOneTime = $scope.findCLICMDIsAlreadyExists("export_"+$scope.switchExportAddType.split("/").join("_")+"_"+$scope.collectorIpAddress, "show flow exporter\n");
            var samplerIsOneTime = $scope.findCLICMDIsAlreadyExists("Sampler "+$scope.samplingMethodType+"_1_"+$scope.samplingMethodRangeType, "show sampler\n");
            if(netFlowFormValidations.validate()){
        		if($scope.netFlowMonitorsGrid._data.length > 0){
                    var interfaceIsOneTime = $filter('filter')($scope.netFlowMonitorsGrid._data, {"SamplerInterFaces":$scope.inputCapIntType});
        		}else{
        			var interfaceIsOneTime = [];
        		}
        		if(interfaceIsOneTime.length == 0){
	        		var netFlowConfigCLI = '';
		        	// CLI command for Record creation (Netflow Template)
		        	if($scope.netFlowTemplateType.indexOf("ApplicationTraffic")!=-1 && !flowRecordIsOneTime){
		        		netFlowConfigCLI += "flow record "+$scope.netFlowTemplateType+"\n";
		        		netFlowConfigCLI += "match ipv4 protocol \n";
		        		netFlowConfigCLI += "match ipv4 source address \n";
		        		netFlowConfigCLI += "match ipv4 destination address \n";
		        		netFlowConfigCLI += "match transport source-port \n";
		        		netFlowConfigCLI += "match transport destination-port \n";
		        		netFlowConfigCLI += "collect transport tcp flags \n";
		        		netFlowConfigCLI += "collect counter packets permanent \n";
		        		netFlowConfigCLI += "collect timestamp sys-uptime first \n";
		        		netFlowConfigCLI += "collect timestamp sys-uptime last \n";
		        		netFlowConfigCLI +=  "exit \n";
		        	}else if($scope.netFlowTemplateType.indexOf("ServerUtilization")!=-1 && !flowRecordIsOneTime){
		        		netFlowConfigCLI += "flow record "+$scope.netFlowTemplateType+"\n";
		        		netFlowConfigCLI += "match ipv4 protocol \n";
		        		netFlowConfigCLI += "match ipv4 source address \n";
		        		netFlowConfigCLI += "match ipv4 destination address \n";
		        		netFlowConfigCLI += "match transport source-port \n";
		        		netFlowConfigCLI += "match transport destination-port \n";
		        		netFlowConfigCLI += "collect interface input \n";
		        		if(!$scope.fullNetFlowSupport){
                            netFlowConfigCLI += "collect interface output \n";
                        }
		        		netFlowConfigCLI += "collect counter packets permanent \n";
		        		netFlowConfigCLI +=  "exit \n";
		        	}else if($scope.netFlowTemplateType.indexOf("Security")!=-1 && !flowRecordIsOneTime){
		        		netFlowConfigCLI += "flow record "+$scope.netFlowTemplateType+"\n";
		        		netFlowConfigCLI += "match ipv4 tos \n";
		        		netFlowConfigCLI += "match ipv4 protocol \n";
		        		netFlowConfigCLI += "match ipv4 source address \n";
		        		netFlowConfigCLI += "match ipv4 destination address \n";
		        		netFlowConfigCLI += "match transport source-port \n";
		        		netFlowConfigCLI += "match transport destination-port \n";
                        if(!$scope.fullNetFlowSupport){
    		        		netFlowConfigCLI += "collect transport icmp ipv4 type \n";
    		        		netFlowConfigCLI += "collect transport icmp ipv4 code \n";
                        }
		        		netFlowConfigCLI += "collect transport tcp flags \n";
		        		netFlowConfigCLI += "collect counter packets permanent \n";
		        		netFlowConfigCLI += "collect timestamp sys-uptime first \n";
		        		netFlowConfigCLI += "collect timestamp sys-uptime last \n";
		        		netFlowConfigCLI +=  "exit \n";
		        	}else if($scope.netFlowTemplateType.indexOf("CapacityPlanning")!=-1 && !flowRecordIsOneTime){
		        		netFlowConfigCLI += "flow record "+$scope.netFlowTemplateType+"\n";
		        		netFlowConfigCLI += "match ipv6 protocol \n";
		        		netFlowConfigCLI += "match ipv6 source address \n";
		        		netFlowConfigCLI += "match ipv6 destination address \n";
		        		netFlowConfigCLI += "match transport source-port \n";
		        		netFlowConfigCLI += "match transport destination-port \n";
		        		netFlowConfigCLI += "collect interface input \n";
		        		if(!$scope.fullNetFlowSupport){
                            netFlowConfigCLI += "collect interface output \n";
                        }
		        		netFlowConfigCLI += "collect counter packets permanent \n";
		        		netFlowConfigCLI +=  "exit \n";
		        	}else if($scope.netFlowTemplateType.indexOf("StealthWatch")!=-1 && !flowRecordIsOneTime){
		        		netFlowConfigCLI += "flow record "+$scope.netFlowTemplateType+"\n";
		        		netFlowConfigCLI += "match datalink mac source address input \n";
		        		netFlowConfigCLI += "match datalink mac destination address input \n";
		        		netFlowConfigCLI += "match ipv4 tos \n";
		        		netFlowConfigCLI += "match ipv4 protocol \n";
		        		netFlowConfigCLI += "match ipv4 source address \n";
		        		netFlowConfigCLI += "match ipv4 destination address \n";
		        		netFlowConfigCLI += "match transport source-port \n";
		        		netFlowConfigCLI += "match transport destination-port \n";
		        		netFlowConfigCLI += "collect transport tcp flags \n";
		        		netFlowConfigCLI += "collect interface input \n";
		        		if(!$scope.fullNetFlowSupport){
                            netFlowConfigCLI += "collect interface output \n";
                        }
		        		netFlowConfigCLI += "collect counter bytes long \n";
		        		netFlowConfigCLI += "collect timestamp sys-uptime first \n";
		        		netFlowConfigCLI += "collect timestamp sys-uptime last \n";
		        		netFlowConfigCLI +=  "exit \n";
		        	}
		        	
		        	var source_interface = $filter('filter')($scope.switchExportAddress, {"text":$scope.switchExportAddType})
		        		,shortNameOfNFTemplate = $filter('filter')($scope.netFlowTemplateDataSource, {"nftValue":$scope.netFlowTemplateType})
		        		,switchExportAddressToHex = $scope.convertIpAddressToHex(source_interface[0].ipAddress.toString())
		        		,collectoIpAddressToHex = $scope.convertIpAddressToHex($scope.collectorIpAddress.toString());
		        	
		        	// CLI command for Exporter (Switch Export IP address)
                    if(!exporterIsOneTime){
    		        	netFlowConfigCLI += "flow exporter export_"+$scope.switchExportAddType.split("/").join("_")+"_"+$scope.collectorIpAddress+" \n";
    		        	netFlowConfigCLI += "destination "+$scope.collectorIpAddress+" \n";
    		        	netFlowConfigCLI += "source "+source_interface[0].name+" \n";
    		        	netFlowConfigCLI +=  "transport udp 2055 \n";
    		        	netFlowConfigCLI +=  "exit \n";
                    }
		        	
		        	// CLI command for Sampling (Sampling Method)
                    if($scope.samplingMethodType !== "fullnetflow" && !samplerIsOneTime){
                        //netFlowConfigCLI += "sampler "+shortNameOfNFTemplate[0].nftShort+"X"+source_interface[0].name+"_"+switchExportAddressToHex+"_"+collectoIpAddressToHex+" \n";
                        netFlowConfigCLI += "sampler "+$scope.samplingMethodType+"_1_"+$scope.samplingMethodRangeType+" \n";
    		        	netFlowConfigCLI += "mode "+$scope.samplingMethodType+" 1 out-of "+$scope.samplingMethodRangeType+" \n";
    		        	netFlowConfigCLI +=  "exit \n";
                    }
		        	
		        	//CLI command for Create a flow monitor
		        	netFlowConfigCLI += "flow monitor "+$scope.monitorUnitName+shortNameOfNFTemplate[0].nftShort+"X"+source_interface[0].name.split("/").join("_")+"_"+switchExportAddressToHex+"_"+collectoIpAddressToHex+$scope.inputCapIntType.replace(/\//g,"_")+" \n";
		        	netFlowConfigCLI += "exporter export_"+$scope.switchExportAddType.split("/").join("_")+"_"+$scope.collectorIpAddress+" \n";
		        	netFlowConfigCLI += "record "+$scope.netFlowTemplateType+" \n";
		        	netFlowConfigCLI += "exit \n";
			        
                    //CLI command for Associate to an interface	
		    var ipType = ($scope.netFlowTemplateType.indexOf("CapacityPlanning")!=-1)?"ipv6":"ip"; 
                    if($scope.samplingMethodType !== "fullnetflow"){
                        netFlowConfigCLI += "interface "+$scope.inputCapIntType+" \n";
    			        netFlowConfigCLI += ipType + " flow monitor "+$scope.monitorUnitName+shortNameOfNFTemplate[0].nftShort+"X"+source_interface[0].name.split("/").join("_")+"_"+switchExportAddressToHex+"_"+collectoIpAddressToHex+$scope.inputCapIntType.replace(/\//g,"_")+" sampler "+$scope.samplingMethodType+"_1_"+$scope.samplingMethodRangeType+" input \n";
    			        netFlowConfigCLI += "exit \n";
                    }else{
                        netFlowConfigCLI += "interface "+$scope.inputCapIntType+" \n";
                        netFlowConfigCLI += ipType + " flow monitor "+$scope.monitorUnitName+shortNameOfNFTemplate[0].nftShort+"X"+source_interface[0].name.split("/").join("_")+"_"+switchExportAddressToHex+"_"+collectoIpAddressToHex+$scope.inputCapIntType.replace(/\//g,"_")+" input \n";
                        netFlowConfigCLI += "exit \n";
                    }
                    var result = requestRoutingService.getConfigCmdOutput(netFlowConfigCLI);
		            if(result==""){
		                notificationService.showNotification(translate('nf_success_msg'),translate('com_config_success_title'),'success');
		            }else{
		                notificationService.showNotification(result.errorResponse,translate('com_config_fail_title'),'error');
		            }
                    $scope.loadGridData();
		        	$scope.manualGridRefresh();
                    $scope.samplingMethodType = $scope.samplingMethodDataSource[0].samplingMethodValue;
                    $scope.inputCapIntType = $scope.inputCaptureInterface[0].interfaceName;
                    $scope.switchExportAddType = $scope.switchExportAddress[0].text;
		            $scope.collectorIpAddress = '';
		            angular.element("#samplerRangeContainer input").val("");
		            $timeout(function(){
		            	netFlowFormValidations.hideMessages();//hiding the validator popup messges.
		            },10);
	        	}else{
                    if(interfaceIsOneTime.length > 0){
    	        		notificationService.showNotification(translate('nf_interface_warning_msg'),translate('nf_config_warning_title'),'error');
                    }
	        	}	
        	}
        }
	}]);
