/**
 Description: HTTP and SNMP Controller
 Copyright (c) 2016 by Cisco Systems, Inc.
 All rights reserved.
 */
app.controller('ManagementCtrl', ['$scope','$timeout', '$filter', 'gridCrudService', 'requestRoutingService','notificationService','validationService','httpEndPointService',
function($scope,$timeout, $filter, gridCrudService, requestRoutingService,notificationService,validationService,httpEndPointService) {
		var translate = $filter("translate");
		
		//HTTP CODE
		
		loadHttp();
		function loadHttp(){
		$scope.disableApplyhttpBtn = true;
		$scope.trustPoints = new kendo.data.ObservableArray([]);		
		var httpStatusList =requestRoutingService.getShowCmdOutput("show ip http server status ","http");
		var trustpointsList = requestRoutingService.getShowCmdOutput("show crypto pki trustpoints status","cryptoTrustPoints");			
		trustpointsList = trustpointsList.ShowCryptoPkiTrustpointsStatus.wnwebdata.trust;
		if (typeof trustpointsList == "object" && !trustpointsList.length)
				trustpointsList = [trustpointsList];
				$scope.trustpointsList = $.map(trustpointsList, function(value, index) {
					return [value];
				});		
		for (var trustpoint in trustpointsList) {
                var trustPoint = trustpointsList[trustpoint];
                $scope.trustPoints.push(trustPoint.TrustPoint);
        }		
		$scope.http = {};
		$scope.https = {};
		$scope.timeoutPolicy = {};
		$scope.trustpoint = {};
		if(httpStatusList.ShowIpHttp.wnwebdata.entity){
			var http = httpStatusList.ShowIpHttp.wnwebdata.entity;
			$scope.http.access = (http.httpaccess == 'Enabled') ? translate('com_enable'):translate('com_disable');
			$scope.http.port = http.httpport;
			$scope.http.existingport = $scope.http.port;
			$scope.https.access = (http.httpsaccess == 'Enabled') ? translate('com_enable'):translate('com_disable');
			$scope.https.port = http.httpsport;
			$scope.https.existingport = $scope.https.port;
			$scope.timeoutPolicy.httpTimeout = http.httpTimeout;
			$scope.timeoutPolicy.serverLifeTime = http.serverLifeTime;
			$scope.timeoutPolicy.maxRequest = http.maxRequest;
			$scope.trustpoint.status = translate('com_enable')
			if (http.trustpoint != "") {
				$scope.trustpoint.status = translate('com_enable');
				$scope.trustpoint.trustPoint = http.trustpoint;
				$scope.trustpoint.existingtrustPoint = $scope.trustpoint.trustPoint;
			}else{
				$scope.trustpoint.status = translate('com_disable');
				$scope.trustpoint.trustPoint = "";
				$scope.trustpoint.existingtrustPoint ="";
			}
		  }
		}
		
		$scope.resethttpFunction = function(){
			angular.element("#httpConfig  span.k-tooltip-validation").hide();
			loadHttp();
		}
		$scope.enableApplyhttpBtn = function(){
			$scope.disableApplyhttpBtn = false;
		}
		var httpValidations = $("#httpConfig").kendoValidator({
				rules : {
					maximum : function(input) {
						var minValue = input.data('maximum');
						if (minValue)
							return input.val() <= Number(minValue);
						return true;
					},
					minimum : function(input) {
						var maxValue = input.data('minimum');
						if (maxValue)
							return input.val() >= Number(maxValue);
						return true;
					},
					httpvalidports : function(input) {
						var minValue = input.data('httpvalidports');
						if (!minValue)
							return true;
						if (input.val() == 80) {
							return true;
						} else {
							if (minValue) {
								return input.val() <= Number(minValue) && input.val() >= 1025;
							}
							return true;
						}
					},
					httpsvalidports : function(input) {
						var minValue = input.data('httpsvalidports');
						if (!minValue)
							return true;
						if (input.val() == 443) {
							return true;
						} else {
							if (minValue) {
								return input.val() <= Number(minValue) && input.val() >= 1025;
							}
							return true;
						}
					}
				}
		}).data("kendoValidator");
		
		
		$scope.tabTog = function(){
			$('#myTabStrip').find('li').removeClass('k-state-default');
		}

		
		$scope.httpApply = function(){
			if (httpValidations.validate()) { 
			var httpCli = ""
			if ($scope.http.access == translate('com_enable')){
				httpCli = httpCli + "ip http server \n ip http port " + $scope.http.port + "\n"
			} else{
				httpCli = httpCli + "no ip http server \n"
			}

			if ($scope.timeoutPolicy.httpTimeout != ""){
				httpCli = httpCli + "ip http timeout-policy idle " + $scope.timeoutPolicy.httpTimeout + " life " + $scope.timeoutPolicy.serverLifeTime + " requests " + $scope.timeoutPolicy.maxRequest + "\n"
			}

			if ($scope.https.access == translate('com_enable')){
				httpCli = httpCli + "ip http secure-server \n ip http secure-port " + $scope.https.port + "\n"
			} else {
				httpCli = httpCli + "no ip http secure-server \n"
			}

			if ($scope.trustpoint.status == translate('com_enable')){				
				if ($scope.trustpoint.trustPoint != "" && $scope.trustpoint.trustPoint !=undefined){
					httpCli = httpCli + "ip http secure-trustpoint " + $scope.trustpoint.trustPoint + "\n"
				}
			}
			if ($scope.trustpoint.status == translate('com_disable')){
				if ($scope.trustpoint.existingtrustPoint != "" && $scope.trustpoint.existingtrustPoint !=undefined)
					httpCli = httpCli + "no ip http secure-trustpoint " + $scope.trustpoint.existingtrustPoint + "\n"
			}
			
			var result = requestRoutingService.getConfigCmdOutput(httpCli);
			if(result==""){
				notificationService.showNotification(translate('http_success_msg'),translate('com_config_success_title'),'success');
			}else{
				notificationService.showNotification(result.errorResponse,translate('com_config_fail_title'),'error');
			}	
		  }
		  loadHttp();
		}
		
		
//SNMP CODE		
		$scope.countCommunity = 0;
        $scope.selectedCommunityArray = [];
        $scope.countUser = 0;
        $scope.selectedUserArray = [];
        $scope.countHost = 0;
        $scope.selectedHostArray = [];
        $scope.snmpHostPristineData = {};
        $scope.snmpCommunityPristineData = {};
        $scope.snmpUserPristineData = {};
        $scope.disableApplyButton = false;
        $scope.communityChanges = false;
        $scope.snmpUserChanges = false;
        $scope.snmpHostChanges = false;
        $scope.cancelOtherTabs = false;
        $scope.version = 'V1';
        $scope.communityGridData = new kendo.data.ObservableArray([]);
        $scope.hostGridData = new kendo.data.ObservableArray([]);
        $scope.userGridData = new kendo.data.ObservableArray([]);
		
        $scope.snmpHostValidaiton = {
            ipvalidation: function (input) {
                if (input.filter("[data-ipvalidation]")) {
                    return true;
                }
                return true;
            },


            reservedipvalidation: function (input) {
                if (input.filter("[data-reservedipvalidation]") && input.attr("name") == 'ipAddress' && input.val()) {
                    var value = input.val();
                    return true;
                }
                return true;
            },
            udpportvalidation: function (input) {
                if (input.filter("[data-udpportvalidation]") && input.attr("name") == 'udpPort') {
                    return true;
                }
                return true;
            },
            namevalidation: function (input) {
                if (input.filter("[data-namevalidation]")) {
                    var value = input.val();
                    return true;
                }
                return true;
            }
        };

        $scope.snmpV3UsersValidations = {
            namevalidation: function (input) {
                if (input.filter("[data-namevalidation]")) {
                    return true;
                }
                return true;
            },


            groupnamevalidation: function (input) {
                if (input.filter("[data-groupnamevalidation]")) {
                    return true;
                }
                return true;
            },
            privprotocolpasswordvalidation: function (input) {
                if (input.is("[name=privPassword]") && input.filter("[data-privprotocolpasswordvalidation]")) {
                    return true;
                }
                return true;
            },
            authprotocolpasswordvalidation: function (input) {
                if (input.is("[name=authPassword]") && input.filter("[data-authprotocolpasswordvalidation]")) {
                    return true;
                }
                return true;
            }
        };

        $scope.snmpCommunityValidation = {
            namevalidation: function (input) {
                if (input.is("[name=Name]") && input.filter("[data-namevalidation]")) {
                    return true;
                }
                return true;
            }
        };

        $scope.isChecked = function (checked, dataItem, grid) {
            if (!grid || grid == '')
                grid = 'Community';
            switch (grid) {
                case 'Community' :
                    if (checked == false) {
                        $scope.countCommunity = $scope.countCommunity - 1;
                        var index = $scope.selectedCommunityArray.indexOf(dataItem);
                        if (index > -1) {
                            $scope.selectedCommunityArray.splice(index, 1);
                        }
                    } else {
                        $scope.countCommunity = $scope.countCommunity + 1;
                        $scope.selectedCommunityArray.push(dataItem);
                    }
                    break;
                case   'User'      :
                    if (checked == false) {
                        $scope.countUser = $scope.countUser - 1;
                        index = $scope.selectedUserArray.indexOf(dataItem);
                        if (index > -1) {
                            $scope.selectedUserArray.splice(index, 1);
                        }
                    } else {
                        $scope.countUser = $scope.countUser + 1;
                        $scope.selectedUserArray.push(dataItem);
                    }
                    break;

                case 'Host':
                    if (checked == false) {
                        $scope.countHost = $scope.countHost - 1;
                        index = $scope.selectedHostArray.indexOf(dataItem);
                        if (index > -1) {
                            $scope.selectedHostArray.splice(index, 1);
                        }
                    } else {
                        $scope.countHost = $scope.countHost + 1;
                        $scope.selectedHostArray.push(dataItem);
                    }
                    break;
            }
            if ($scope.selectedCommunityArray.length > 0 || $scope.selectedUserArray.length > 0 || $scope.selectedHostArray.length > 0) {
                $scope.enableDeleteBtn = false;
            } else {
                $scope.enableDeleteBtn = true;
            }
        };

        $scope.snmpModel = {
            status: translate('com_enable'),
            systemLocation: '',
            systemContact: '',
            globalTrap: '',
            logging: ''
        };

       
		var snmpValidations = $("#snmpForm").kendoValidator({
			rules: {
				
			}
		}).data("kendoValidator");
		

        $scope.versionChange = function (dataItem) {
            $scope.version = dataItem.version;
        };

        $scope.rowSelected = function (selected, data, dataItem, columns) {
            $scope.enableDeleteBtn = false;
			$scope.disableApplyButton = true;
            if ($scope.snmpTabStrip.select().index() == 1) {
                if ($scope.communityGridDataSource.hasChanges() === false) {
                    $scope.communityChanges = false;
                    $scope.disableApplyButton = false;
                } else if ($scope.communityGridDataSource.hasChanges() === true) {
                    $scope.communityChanges = true;
                    $scope.disableApplyButton = false;
                    preventCommunityGridPaginationAction = false;
                }
            } else if ($scope.snmpTabStrip.select().index() == 2) {
                if ($scope.userGridDataSource.hasChanges() === false) {
                    $scope.snmpUserChanges = false;
                    $scope.disableApplyButton = false;
                } else if ($scope.userGridDataSource.hasChanges() === true) {
                    $scope.snmpUserChanges = true;
                    $scope.disableApplyButton = false;
                    preventUsersGridPaginationAction = false;
                }
            } else if ($scope.snmpTabStrip.select().index() == 3) {
                if ($scope.hostGridDataSource.hasChanges() === false) {
                    $scope.snmpHostChanges = false;
                    $scope.disableApplyButton = false;
                } else if ($scope.hostGridDataSource.hasChanges() === true) {
                    $scope.snmpHostChanges = true;
                    $scope.disableApplyButton = false;
                    preventHostsGridPaginationAction = false;
                }
            }
        };
		
		$scope.enableApplybtn = function(){		
			if($scope.snmpModel.status == "Disable") $scope.disableApplyButton = true;
			else $scope.disableApplyButton = false;
            $scope.snmpModel.displayAllGrid = ($scope.snmpModel.status == 'not enabled') ? translate('com_disable') : translate('com_enable');
		}

		
		$scope.IsShow = false;
		$scope.disableApply = function(){
			if($scope.communityGridData.length == 0 && $scope.userGridData.length == 0 && $scope.hostGridData.length == 0) $scope.disableApplyButton = true;
			else $scope.disableApplyButton = false;
			$scope.IsShow = false;
		}
		
        $scope.disableApplyCommunity = function () {
            $scope.disableApplyButton = true;
            var communityIndex = 0;
            if ($scope.communityGridData.length > 0) {
                if ($scope.communityGrid._data[communityIndex].Name === "") {
                    return $scope.communityGrid.dataSource.remove($scope.communityGrid._data[communityIndex]);
                }
            }
            if ($scope.communityChanges === true) {
                $scope.disableApplyButton = false;
            } else if ($scope.communityChanges === false) {
                $scope.disableApplyButton = true;
            }
			$scope.IsShow = true;
        };

        $scope.disableApplyUser = function () {
            $scope.disableApplyButton = true;
            var communityIndex = 0;
            if ($scope.snmpUserGrid.length > 0) {
                if ($scope.snmpUserGrid._data[communityIndex].userName === "") {
                    return $scope.snmpUserGrid.dataSource.remove($scope.snmpUserGrid._data[communityIndex]);
                }
            }
            if ($scope.snmpUserChanges === true) {
                $scope.disableApplyButton = false;
            } else if ($scope.snmpUserChanges === false) {
                $scope.disableApplyButton = true;
            }
			$scope.IsShow = true;
        };

        $scope.disableApplyHost = function () {
            $scope.disableApplyButton = true;
            var communityIndex = 0;
            if ($scope.snmpHostGrid.length > 0) {
                if ($scope.snmpHostGrid._data[communityIndex].ipAddress === "") {
                    return $scope.snmpHostGrid.dataSource.remove($scope.snmpHostGrid._data[communityIndex]);
                }
            }
            if ($scope.snmpHostChanges === true) {
                $scope.disableApplyButton = false;
            } else if ($scope.snmpHostChanges === false) {
                $scope.disableApplyButton = true;
            }
			$scope.IsShow = true;
        };

        
        function filter_snmp_community(data1, data2) {
            var a = angular.copy(data1);
            var b = angular.copy(data2);
            for (var i = 0, len = a.length; i < len; i++) {
                for (var j = 0, len2 = b.length; j < len2; j++) {
                    if (a[i].Name === b[j].Name && a[i].AccessMode === b[j].AccessMode) {
                        b.splice(j, 1);
                        len2 = b.length;
                    }
                }
            }
            return b;
        }

        function filter_snmp_user(data1, data2) {
            var a = angular.copy(data1);
            var b = angular.copy(data2);
            for (var i = 0, len = a.length; i < len; i++) {
                for (var j = 0, len2 = b.length; j < len2; j++) {
                    if (a[i].userName === b[j].userName && a[i].groupName === b[j].groupName && a[i].privProtocol === b[j].privProtocol && a[i].authProtocol === b[j].authProtocol && a[i].authPassword === b[j].authPassword && a[i].privPassword === b[j].privPassword) {
                        b.splice(j, 1);
                        len2 = b.length;
                    }
                }
            }
            return b;
        }

        function filter_snmp_host(data1, data2) {
            var a = angular.copy(data1);
            var b = angular.copy(data2);
            for (var i = 0, len = a.length; i < len; i++) {
                for (var j = 0, len2 = b.length; j < len2; j++) {
                    if (a[i].ipAddress === b[j].ipAddress && a[i].udpPort === b[j].udpPort && a[i].version === b[j].version && a[i].type === b[j].type && a[i].communityName === b[j].communityName && a[i].securityLevel === b[j].securityLevel) {
                        b.splice(j, 1);
                        len2 = b.length;
                    }
                }
            }
            return b;
        }

        $scope.apply = function () {
            $scope.returnJson = {
                createSnmp: [],
                deleteSnmp: [],
                snmpTab: ""
            };
            if ($scope.snmpTabStrip.select().index() == 1) {
				if ($scope.snmpCommunityValidator.validate()) {
					var pristineDataCommunity = angular.copy($scope.snmpCommunityPristineData);
					var currentDataTemp = angular.copy($scope.communityGrid.dataSource._data);
					var createdSnmp_community = filter_snmp_community(pristineDataCommunity, currentDataTemp);
					var deletedSnmp_community = filter_snmp_community(currentDataTemp, pristineDataCommunity);
					var communityCLI = "";
					for (var j = 0; j < deletedSnmp_community.length; j++) {
						communityCLI += "no snmp-server community " + deletedSnmp_community[j].Name + " \n";
					}
					for (var i = 0; i < createdSnmp_community.length; i++) {
						if (createdSnmp_community[i].AccessMode == "Read Only")
							communityCLI += "snmp-server community " + createdSnmp_community[i].Name + " ro \n";
						if (createdSnmp_community[i].AccessMode == "Read/Write")
							communityCLI += "snmp-server community " + createdSnmp_community[i].Name + " rw \n";
					}
					var result = requestRoutingService.getConfigCmdOutput(communityCLI);
					if(result==""){
						notificationService.showNotification(translate('snmp_success_msg'),translate('com_config_success_title'),'success');
					}else{
						notificationService.showNotification(result.errorResponse,translate('com_config_fail_title'),'error');
					}	
					$scope.communityChanges = false;
						var communityGridData = angular.copy($scope.communityGrid.dataSource._data);					
						$scope.communityGridDataSource = new kendo.data.DataSource({
							pageSize: 10,
							data: $scope.communityGridData
						});
					
				 }
				 else return false;
                
            }
            else if ($scope.snmpTabStrip.select().index() == 2) {
				if($scope.snmpV3UserValidator.validate()){
					var pristineDataUser = angular.copy($scope.snmpUserPristineData);
					var currentDataTemp = angular.copy($scope.snmpUserGrid.dataSource._data);
					var createdSnmp_user = filter_snmp_user(pristineDataUser, currentDataTemp);
					var deletedSnmp_user = filter_snmp_user(currentDataTemp, pristineDataUser);
					var userCLI = "";
					for (var j = 0; j < deletedSnmp_user.length; j++) {
						userCLI += "no snmp-server user " + deletedSnmp_user[j].userName + " " + deletedSnmp_user[j].groupName + " v3 \n";
					}
					for (var i = 0; i < createdSnmp_user.length; i++) {
						var privProtocolType = "None";
						if (createdSnmp_user[i].authProtocol == "None")
							userCLI = userCLI + "snmp-server user " + createdSnmp_user[i].userName + " " + createdSnmp_user[i].groupName + " v3 \n";
						if (createdSnmp_user[i].privProtocol == "3DES")
							privProtocolType = "3des";
						if (createdSnmp_user[i].privProtocol == "DES")
							privProtocolType = "des";
						if (createdSnmp_user[i].privProtocol == "AES128")
							privProtocolType = "aes 128";
						if (createdSnmp_user[i].privProtocol == "AES192")
							privProtocolType = "aes 192";
						if (createdSnmp_user[i].privProtocol == "AES256")
							privProtocolType = "aes 256";
						if (createdSnmp_user[i].authProtocol == "MD5") {
							if (privProtocolType == "None") {
								if (createdSnmp_user[i].authPassword != "")
									userCLI = userCLI + "snmp-server user " + createdSnmp_user[i].userName + " " + createdSnmp_user[i].groupName + " v3 auth md5 " + createdSnmp_user[i].authPassword + " \n"
							}
							else {
								if ((createdSnmp_user[i].privPassword != ""))
									userCLI = userCLI + "snmp-server user " + createdSnmp_user[i].userName + " " + createdSnmp_user[i].groupName + " v3 auth md5 " + createdSnmp_user[i].privPassword + " priv " + privProtocolType + " " + createdSnmp_user[i].authPassword + " \n"
							}
						}

						if (createdSnmp_user[i].authProtocol == "SHA") {
							if (privProtocolType == "None") {
								if (createdSnmp_user[i].authPassword)
									userCLI = userCLI + "snmp-server user " + createdSnmp_user[i].userName + " " + createdSnmp_user[i].groupName + " v3 auth sha " + createdSnmp_user[i].authPassword + " \n"
							}
							else {
								if (createdSnmp_user[i].privPassword)
									userCLI = userCLI + "snmp-server user " + createdSnmp_user[i].userName + " " + createdSnmp_user[i].groupName + " v3 auth sha " + createdSnmp_user[i].privPassword + " priv " + privProtocolType + " " + createdSnmp_user[i].authPassword + " \n"
							}
						}

					}

					var result = requestRoutingService.getConfigCmdOutput(userCLI);
					if(result==""){
						notificationService.showNotification(translate('snmp_success_msg'),translate('com_config_success_title'),'success');
					}else{
						notificationService.showNotification(result.errorResponse,translate('com_config_fail_title'),'error');
					}	
					if (createdSnmp_user.length > 0) {
						$scope.fieldEmpty = false;
						if (!$scope.snmpUserGrid.editable) {
							$scope.disableApplyButton = true;

						} else {
							$scope.disableApplyButton = true;
							$scope.snmpUserGrid.editable.end();
						}
					}
					$scope.snmpUserChanges = false;
					
					var userGridData = angular.copy($scope.snmpUserGrid.dataSource._data);
					$scope.userGridDataSource = new kendo.data.DataSource({
						pageSize: 10,
						data: $scope.userGridData
					});
				}
				else return false;
            }
            else if ($scope.snmpTabStrip.select().index() == 3) {
				if($scope.snmpHostValidator.validate()){
                var pristineData = angular.copy($scope.snmpHostPristineData);
                var currentDataTemp = angular.copy($scope.snmpHostGrid.dataSource._data);
                var createdSnmp_host = filter_snmp_host(pristineData, currentDataTemp);
                var deletedSnmp_host = filter_snmp_host(currentDataTemp, pristineData);
                var hostCLI = "";
                for (var j = 0; j < deletedSnmp_host.length; j++) {
                    if (deletedSnmp_host[j].version == "v1")
                        hostCLI = hostCLI + "no snmp-server host " + deletedSnmp_host[j].ipAddress + " trap version 1 " + deletedSnmp_host[j].communityName + " udp-port " + deletedSnmp_host[j].udpPort + " \n";

                    if (deletedSnmp_host[j].version == "v2c")
                        hostCLI = hostCLI + "no snmp-server host " + deletedSnmp_host[j].ipAddress + " " + deletedSnmp_host[j].type + " version 2c " + deletedSnmp_host[j].communityName + " udp-port " + deletedSnmp_host[j].udpPort + " \n";

                    if (deletedSnmp_host[j].version == "v3")
                        hostCLI = hostCLI + "no snmp-server host " + deletedSnmp_host[j].ipAddress + " " + deletedSnmp_host[j].type + " version 3 " + deletedSnmp_host[j].securityLevel + " " + deletedSnmp_host[j].communityName + " udp-port " + deletedSnmp_host[j].udpPort + " \n";
                }
                for (var i = 0; i < createdSnmp_host.length; i++) {
                    if (!createdSnmp_host[i].udpPort)
                        createdSnmp_host[i].udpPort = "162";
                    if (createdSnmp_host[i].version == "v1")
                        hostCLI = hostCLI + "snmp-server host " + createdSnmp_host[i].ipAddress + " trap version 1 " + createdSnmp_host[i].communityName + " udp-port " + createdSnmp_host[i].udpPort + " \n";
                    if (createdSnmp_host[i].version == "v2c")
                        hostCLI = hostCLI + "snmp-server host " + createdSnmp_host[i].ipAddress + " " + createdSnmp_host[i].type + " version 2c " + createdSnmp_host[i].communityName + " udp-port " + createdSnmp_host[i].udpPort + " \n";
                    if (createdSnmp_host[i].version == "v3")
                        hostCLI = hostCLI + "snmp-server host " + createdSnmp_host[i].ipAddress + " " + createdSnmp_host[i].type + " version 3 " + createdSnmp_host[i].securityLevel + " " + createdSnmp_host[i].communityName + " udp-port " + createdSnmp_host[i].udpPort + " \n";
                }
                if (createdSnmp_host.length > 0) {
                    if (!$scope.snmpHostGrid.editable) {
                        $scope.disableApplyButton = true;
                    } else {
                        $scope.disableApplyButton = true;
                        $scope.snmpHostGrid.editable.end();
                    }
                }
                var result = requestRoutingService.getConfigCmdOutput(hostCLI);
                if(result==""){
    				notificationService.showNotification(translate('snmp_success_msg'),translate('com_config_success_title'),'success');
    			}else{
    				notificationService.showNotification(result.errorResponse,translate('com_config_fail_title'),'error');
    			}	
               var tabSNMP ="General";
                if ($scope.snmpTabStrip.select().index() ==1 ) {
                    tabSNMP = "Communities";
                }else if ($scope.snmpTabStrip.select().index() ==2 ) {
                    tabSNMP = "SNMP V3 Users";
                }else if ($scope.snmpTabStrip.select().index() ==3 ) {
                    tabSNMP = "SNMP Host";
                }
                $scope.returnJson.snmpTab = tabSNMP;
                $scope.snmpHostChanges = false;
					var hostGridData = angular.copy($scope.snmpHostGrid.dataSource._data);
					$scope.hostGridDataSource = new kendo.data.DataSource({
						pageSize: 10,
						data: $scope.hostGridData
					});
				
				}
				else return false;

            }
            else if ($scope.snmpTabStrip.select().index() == 0) {
				
				var generalCLI = "";
                if ($scope.snmpModel["status"] == translate('com_disable'))
                    generalCLI = generalCLI + " no snmp-server \n";
                else {                	
                    if ($scope.snmpModel["systemLocation"]) {
                        generalCLI = generalCLI + "snmp-server location " + $scope.snmpModel["systemLocation"] + " \n";
                    }
                    else {
                        generalCLI = generalCLI + "no snmp-server location \n"
                    }
                    if ($scope.snmpModel["systemContact"]) {
                        generalCLI = generalCLI + "snmp-server contact " + $scope.snmpModel["systemContact"] + " \n";
                    }
                    else {
                        generalCLI = generalCLI + "no snmp-server contact \n";
                    }

                    if ($scope.snmpModel["globalTrap"] == translate('com_enable')) {
                        generalCLI = generalCLI + "snmp-server enable traps \n";
                    }
                    else {
                        generalCLI = generalCLI + "no snmp-server enable traps \n";
                    }
                    	
                }
				if($scope.communityGridData.length == 0 && $scope.userGridData.length == 0 && $scope.hostGridData.length == 0) 
				{
					$scope.disableApplyButton = true;
				}
				else {
					$scope.disableApplyButton = false;
					var result = requestRoutingService.getConfigCmdOutput(generalCLI);
					if(result==""){
						notificationService.showNotification(translate('snmp_success_msg'),translate('com_config_success_title'),'success');
					}else{
						notificationService.showNotification(result.errorResponse,translate('com_config_fail_title'),'error');
					}	
				}	
               
            }

           if ($scope.snmpTabStrip.select().index() == 1) {
                $scope.snmpCommunityPristineData = {};
                $scope.snmpCommunityPristineData = angular.copy($scope.communityGrid.dataSource._data);
                $scope.communityGridDataSource.sync();
                $scope.cancelOtherTabs = true;
				$scope.enableDeleteBtn = true;

            }
            else if ($scope.snmpTabStrip.select().index() == 2) {
                $scope.snmpUserPristineData = {};
                $scope.snmpUserPristineData = angular.copy($scope.snmpUserGrid.dataSource._data);
                $scope.userGridDataSource.sync();
                $scope.cancelOtherTabs = true;
				$scope.enableDeleteBtn = true;
            }
            else if ($scope.snmpTabStrip.select().index() == 3) {
                $scope.snmpHostPristineData = {};
                $scope.snmpHostPristineData = angular.copy($scope.snmpHostGrid.dataSource._data);
                $scope.hostGridDataSource.sync();
                $scope.cancelOtherTabs = true;
				$scope.enableDeleteBtn = true;
            }
            
            $scope.enableDeleteButton = true;
			if(snmpValidations.validate()) $scope.disableApplyButton = true;

			if ($scope.snmpTabStrip.select().index() == 0 || $scope.snmpTabStrip.select().index() == 3) $scope.loadGridData();
        };

        $scope.showToasters = function (data) {
            validationService.showToasterMessage(data, validationService.WSMA_MESSAGE);
        };
        $scope.cancel = function () {
            $scope.confirmationWindow.close();
        };

        //All Variable Declrations are being done here

        $scope.enableDeleteBtn = true;

        $scope.communityAccessModeOptions = ['Read Only', 'Read/Write'];

        $scope.authenticationProtocolOptions = new kendo.data.DataSource({
            data: [
                {
                    nameAuth: "None",
                    valueAuth: "None"
                },
                {
                    nameAuth: "MD5",
                    valueAuth: "MD5"
                },
                {
                    nameAuth: "SHA",
                    valueAuth: "SHA"
                }
            ]
        })
        $scope.privacyProtocolOptions = new kendo.data.DataSource({
            data: [
                {
                    namePriv: "None",
                    valuePriv: "None"
                },
                {
                    namePriv: "3DES",
                    valuePriv: "3DES"
                },
                {
                    namePriv: "AES128",
                    valuePriv: "AES128"
                },
                {
                    namePriv: "AES192",
                    valuePriv: "AES192"
                },
                {
                    namePriv: "AES256",
                    valuePriv: "AES256"
                },
                {
                    namePriv: "DES",
                    valuePriv: "DES"
                }
            ]
        })

        $scope.snmpVersionOptions = new kendo.data.DataSource({
            data: [
                {
                    name: "V1",
                    value: "v1"
                },
                {
                    name: "V2C",
                    value: "v2c"
                },
                {
                    name: "V3",
                    value: "v3"
                }
            ]
        })
        $scope.securityLevelOptions = new kendo.data.DataSource({
            data: [
                {
                    name: "Auth",
                    value: "auth"
                },
                {
                    name: "NoAuth",
                    value: "noauth"
                },
                {
                    name: "Priv",
                    value: "priv"
                }
            ]
        })
        $scope.messageTypeOptionsV1 = new kendo.data.DataSource({
            data: [
                {
                    name: "traps",
                    value: "traps"
                }
            ]
        })
        $scope.messageTypeOptionsV2andV3 = new kendo.data.DataSource({
            data: [
                {
                    name: "traps",
                    value: "traps"
                },
                {
                    name: "informs",
                    value: "informs"
                }
            ]
        })
        $scope.messageTypeOptions = angular.copy($scope.messageTypeOptionsV1);

        var preventCommunityGridPaginationAction = false;
		var hdrTmpCommunityName=translate("management_snmp_community_name") + " <tooltip helptext='" + translate("help_SNMP_community_name") +"' position='top'></tooltip>";
		var hdrTmpAccessMode=translate("management_snmp_community_mode") + " <tooltip helptext='" + translate("help_SNMP_access_mode") +"' position='top'></tooltip>";
		
		var snmpnameMsg = translate("management_snmp_name_required");
		var snmpgrpnameMsg = translate("management_snmp_grpname");
		var snmppasswordMsg = translate("management_snmp_password_required");
		var snmpusernameMsg = translate("management_snmp_username");
		var snmpipMsg = translate("management_snmp_ipaddress_required");
		var snmpcomnameMsg = translate("management_snmp_comname_required");
		$scope.communityGridDataSource = new kendo.data.DataSource({
					pageSize: 10,
					data: $scope.communityGridData,
					schema: {
						model: {
							id: "Name",
							fields: {
								Name: {
									validation: {
										required: true
									}
								},
								AccessMode: {}
							}
						}
					},
					requestStart: function (e) { //prevent grid navigation
						if (preventCommunityGridPaginationAction) {
							e.preventDefault();
						}
					}					
				});	
        $scope.communityGridOptions = {
            editable: true,
            edit: function () {
                preventCommunityGridPaginationAction = true;
            },
            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: true,
                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")
		        }
			},
            selectable: true,
            columns: [
                {
                    "template": "<input type=\"checkbox\"  ng-model=\"checkedCommunity\" ng-click=\"isChecked(checkedCommunity,dataItem,'Community')\"  />",
                    sortable: false,
                    width: 10
                },
                {
                    field: "Name",
		            title: translate("management_snmp_community_name"),
                    headerTemplate : hdrTmpCommunityName,
                    width: 50,
                    editor: function (container, options) {
                        container.append(angular.element('<input class="k-textbox form-control" id="Name" name="Name" required  data-required-msg="'+snmpnameMsg+'" data-namevalidation   data-bind="' + options.field + '" />'));
                    }
                },
                {
                    field: "AccessMode",
                    width: 20,
                    title : translate("management_snmp_community_mode"),
                    headerTemplate : hdrTmpAccessMode,
                    editor: function (container, options) {
                        container.append(angular.element('<select kendo-drop-down-list="AccessMode" name="AcessMode" id="AccessMode" k-data-source="communityAccessModeOptions" data-bind="value:' + options.field + '" ></select>'));
                    }
                }
            ]
        };

		 $scope.authProtocolChange = function (e) {

            var passwordColumn = angular.element(angular.element(e.sender.element).parent().parent().parent().find("td")[4]);
            passwordColumn.empty();
            var model = $scope.snmpUserGrid._modelForContainer(passwordColumn);
            if (e.sender._selectedValue == "MD5" || e.sender._selectedValue == "SHA") {
                $("<input type='password' class='k-text-box form-control fieldinput margin-top-05' required data-required-msg='{{'management_snmp_password_required' | translate}}' data-bind='value:authPassword'>").appendTo(passwordColumn).element
            } else {

            }
            kendo.bind(passwordColumn, model);
        };

        $scope.privProtocolChange = function (e) {

            var passwordColumn = angular.element(angular.element(e.sender.element).parent().parent().parent().find("td")[6]);
            passwordColumn.empty();
            var model = $scope.snmpUserGrid._modelForContainer(passwordColumn);
            if (e.sender._old.toUpperCase() == "DES" || e.sender._old.toUpperCase() == "3DES" || e.sender._old.toUpperCase() == "AES128" || e.sender._old.toUpperCase() == "AES192" || e.sender._old.toUpperCase() == "AES256") {
                $("<input type='password' name='authPassword' class='k-text-box form-control field-input margin-top-05' required data-required-msg='{{'management_snmp_password_required' | translate}}' data-bind='value:privPassword'>").appendTo(passwordColumn).element
            } else {

            }
            kendo.bind(passwordColumn, model);
        };
        
        var preventUsersGridPaginationAction = false;
        var hdrTmpGroupName=translate("management_snmp_v3user_group") + " <tooltip helptext='" + translate("help_SNMP_group") +"' position='top'></tooltip>";
        var hdrTmpAuthProtocol=translate("management_snmp_v3user_auth_protocol") + " <tooltip helptext='" + translate("help_SNMP_auth_protocol") +"' position='top'></tooltip>";
        var hdrTmpPrivProtocol=translate("management_snmp_v3user_priv_protocol") + " <tooltip helptext='" + translate("help_SNMP_priv_protocol") +"' position='top'></tooltip>";
		
		
        $scope.userGridOptions = {
            editable: true,
            edit: function () {
                preventUsersGridPaginationAction = true;
            },
            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:true,
                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")
		        }
			},
            selectable: true,
            columns: [
                {

                    "template": "<input type=\"checkbox\" ng-model=\"checkedUser\" ng-click=\"isChecked(checkedUser,dataItem,'User')\"  />",
                    sortable: false,
                    width: 3
                },
                {
                    field: "userName",
                    title : translate("management_snmp_v3user_name"),
                    width: 5,
                    editor: function (container, options) {
                        container.append(angular.element('<input class="k-text-box form-control" name="userName" id="userName" required data-required-msg="'+snmpusernameMsg+'" data-namevalidation  />'));
                    }
                },
                {
                    field: "groupName",
                    title : translate("management_snmp_v3user_group"),
                    headerTemplate : hdrTmpGroupName,
                    width: 5,
                    editor: function (container, options) {
                        container.append(angular.element('<input required data-required-msg="'+snmpgrpnameMsg+'"  data-groupnamevalidation class="k-textbox" name="groupName" id="groupName" />'));
                    }
                },
                {
                    field: "authProtocol",
                    title : translate("management_snmp_v3user_auth_protocol"),
                    headerTemplate : hdrTmpAuthProtocol,
                    width: 5,
                    editor: function (container, options) {
                        container.append(angular.element('<select kendo-drop-down-list="authProtocol" name="authProtocol" id="authProtocol" k-data-source="authenticationProtocolOptions" k-data-text-field="\'nameAuth\'" k-data-value-field="\'valueAuth\'" k-on-change="authProtocolChange(kendoEvent)" data-bind="value:' + options.field + '"></select>'));
                    }
                },
                {
                    field: "authPassword",
                    title : translate("management_snmp_v3user_auth_password"),
                    width: 5,
                    template: "#if (authProtocol == 'None' || authProtocol == '') { # <div>None </div> # }else{# <div>***** </div> #} #",
                    editor: function (container, options) {
                        if (options.model.authProtocol.toUpperCase() == "SHA".toUpperCase() || options.model.authProtocol.toUpperCase() == "MD5".toUpperCase()) {
                            container.append(angular.element('<div><input type="password" required data-required-msg="'+snmppasswordMsg+'" class="k-text-box form-control fieldinput margin-top-05" data-bind="value:' + options.field + '"/>'));
                        } else {
                            container.append(angular.element('<div>None </div>'));
                        }
                    }
                },
                {
                    field: "privProtocol",
                    title : translate("management_snmp_v3user_priv_protocol"),
                    headerTemplate : hdrTmpPrivProtocol,
                    width: 5,
                    editor: function (container, options) {
                        if (options.model.authProtocol.toUpperCase() == "SHA".toUpperCase() || options.model.authProtocol.toUpperCase() == "MD5".toUpperCase()) {
                            container.append(angular.element('<select kendo-drop-down-list="privProtocol" name="privProtocol" id="privProtocol" k-data-source="privacyProtocolOptions" k-data-text-field="\'namePriv\'" k-data-value-field="\'valuePriv\'" k-on-change="privProtocolChange(kendoEvent)" data-bind="value:' + options.field + '"></select>'));
                        } else {
                            container.append(angular.element('<div>None </div>'));
                        }
                    }
                },
                {
                    field: "privPassword",
                    title : translate("management_snmp_v3user_priv_password"),
                    width: 5,
                    template: "#if (authProtocol == ''  || authProtocol == 'None'  ||  privProtocol == 'None' ||  privProtocol == '') { # <div>None </div> # }else{# <div>***** </div> #} #",
                    editor: function (container, options) {
                        if (options.model.authProtocol.toUpperCase() != "None".toUpperCase() && options.model.privProtocol.toUpperCase() != "None".toUpperCase()) {
                            container.append(angular.element('<input type="password" class="k-text-box form-control fieldinput margin-top-05" required data-required-msg="'+snmppasswordMsg+'" data-bind="value: privPassword"  data-bind="value:' + options.field + '">'));
                        } else {
                            container.append(angular.element('<div>None </div>'));
                        }
                    }
                }
            ]

        };
		

        var preventHostsGridPaginationAction = false;
        var hdrTmpIPAddress=translate("management_snmp_host_ipaddress") + " <tooltip helptext='" + translate("help_SNMP_IP_address") +"' position='top'></tooltip>";
        var hdrTmpUdpPort=translate("management_snmp_host_port") + " <tooltip helptext='" + translate("help_SNMP_port") +"' position='top'></tooltip>";
        var hdrTmpVersion=translate("management_snmp_host_version") + " <tooltip helptext='" + translate("help_SNMP_version") +"' position='top'></tooltip>";
        var hdrTmpType=translate("management_snmp_host_type") + " <tooltip helptext='" + translate("help_SNMP_type") +"' position='top'></tooltip>";
		
        $scope.hostGridOptions = {
            editable: "inline",
            edit: function () {
                preventHostsGridPaginationAction = true;
            },
            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:true,
                pageSizes: gridCrudService.grid_page_sizes, 
                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")
		        }
			},
            selectable: true,
            columns: [
                {
                    "template": "<input type=\"checkbox\"  ng-model=\"checkedHost\" ng-click=\"isChecked(checkedHost,dataItem,'Host')\"  />",
                    sortable: false,
                    width: 2
                },
                {
                    field: "ipAddress",
                    title : translate("management_snmp_host_ipaddress"),
                    headerTemplate : hdrTmpIPAddress,
                    width: 6,
                    editor: function (container, options) {
                        container.append(angular.element('<input class="k-text-box form-control" name="ipAddress" id="ipAddress" required data-required-msg="'+snmpipMsg+'" data-reservedipvalidation data-ipvalidation/>'));
                    }
                },
                {
                    field: "udpPort",
                    title : translate("management_snmp_host_port"),
                    headerTemplate : hdrTmpUdpPort,
                    width: 4,
                    editor: function (container, options) {
                        container.append(angular.element('<input kendo-numeric-textbox data-udpportvalidation="0-65536" name="udpPort" id="udpPort"  placeholder="162"  />'));
                    }
                },
                {
                    field: "version",
                    title : translate("management_snmp_host_version"),
                    headerTemplate : hdrTmpVersion,
                    width: 4,
                    editor: function (container, options) {
                        container.append(angular.element('<select kendo-drop-down-list="version" name="version" id="version"  k-data-source="snmpVersionOptions" k-data-text-field="\'name\'" k-data-value-field="\'value\'" k-on-change="versionChange(dataItem )" data-bind="value:' + options.field + '"></select>'));
                    }
                },
                {
                    field: "type",
                    title : translate("management_snmp_host_type"),
                    headerTemplate : hdrTmpType,
                    width: 4,
                    editor: function (container, options) {
                        var versionValue = options.model.version;
                        $scope.messageTypeOptions = (versionValue.toUpperCase() == 'v1'.toUpperCase()) ? new kendo.data.DataSource({
                            data: [
                                {
                                    name: "traps",
                                    value: "traps"
                                }
                            ]
                        }) : new kendo.data.DataSource({
                            data: [
                                {
                                    name: "traps",
                                    value: "traps"
                                },
                                {
                                    name: "informs",
                                    value: "informs"
                                }
                            ]
                        })
                        container.append(angular.element('<select kendo-drop-down-list name="type" id="type"  k-data-source="messageTypeOptions" k-data-text-field="\'name\'"  k-data-value-field="\'value\'" data-bind="value:' + options.field + '"></select>'));
                    }
                },
                {
                    field: "communityName",
                    title : translate("management_snmp_host_community"),
                    width: 5,
                    editor: function (container, options) {
                        container.append(angular.element('<input class="k-textbox form-control" name="communityName" id="communityName"  required data-required-msg="'+snmpcomnameMsg+'" data-namevalidation/>'));
                    }
                },
                {
                    field: "securityLevel",
                    title : translate("management_snmp_host_security"),
                    width: 4,
                    editor: function (container, options) {
                        var versionValue = options.model.version;
						options.model.securityLevel == "" ? options.model.securityLevel = "auth" : angular.noop();
						$scope.securityShow = false;
						$scope.version = 'V1';
						$scope.$watch('version', function(nVer, oVer){
							if (nVer.toUpperCase() == 'V3') {
								$scope.securityShow = true;
							}else{
								$scope.securityShow = false;
							}
						});
						container.append(angular.element('<select ng-show="securityShow" kendo-drop-down-list name="securityLevel" id="securityLevel" k-data-source="securityLevelOptions"  k-data-text-field="\'name\'" k-data-value-field="\'value\'" data-bind="value:' + options.field + '"  ></select>'));
                    }
                }
            ]

        };

		
			
		$scope.addBtnFunction = function (value) {
            $scope.disableApplyButton = false;
            if ($scope.snmpTabStrip.select().index() == 1) {
                $scope.cancelOtherTabs = false;
                if ($scope.snmpCommunityValidator.validate()) {
                    $scope.communityGrid.addRow();
                    $scope.communityChanges = true;
                    var newRowIndex = $scope.communityGridData.map(function (e) {
                        return e.Name;
                    }).indexOf("");
                    $scope.communityGridData[0].AccessMode = $scope.communityAccessModeOptions[0];
					$timeout(function() {
					angular.element("#communityGrid table tbody tr:nth-child(1) td:nth-child(2)").click();
					});
                }
            } else if ($scope.snmpTabStrip.select().index() == 2) {
                $scope.cancelOtherTabs = false;
                if ($scope.snmpV3UserValidator.validate()) {
                    $scope.snmpUserGrid.addRow();
                    $scope.snmpUserChanges = true;
                    var newRowIndex = $scope.userGridData.map(function (e) {
                        return e.userName;
                    }).indexOf("");
                    $scope.userGridData[newRowIndex].privProtocol = $scope.privacyProtocolOptions.options.data[0].valuePriv;
                    $scope.userGridData[newRowIndex].authProtocol = $scope.authenticationProtocolOptions.options.data[0].valueAuth;
					$timeout(function() {
					angular.element("#snmpUserGrid table tbody tr:nth-child(1) td:nth-child(2)").click();
					});
                }
            } else if ($scope.snmpTabStrip.select().index() == 3) {
                $scope.cancelOtherTabs = false;
                if ($scope.snmpHostValidator.validate()) {
                    $scope.snmpHostGrid.addRow();
                    $scope.snmpHostChanges = true;
                    var newRowIndex = $scope.hostGridData.map(function (e) {
                        return e.ipAddress;
                    }).indexOf("");
                    $scope.hostGridData[0].version = $scope.snmpVersionOptions.options.data[0].value;
                    $scope.hostGridData[0].type = $scope.messageTypeOptionsV1.options.data[0].value;
                }
            }
        };

        $scope.deleteBtnFunction = function () {
            $scope.disableApplyButton = false;
            switch ($scope.snmpTabStrip.select().index()) {
                case 3:
                    if ($scope.countHost > 0) {
                        for (var host = 0; host < $scope.selectedHostArray.length; host++) {
                            $scope.snmpHostGrid.dataSource.remove($scope.selectedHostArray[host]);
                            $scope.snmpHostChanges = true;
                        }
                        $scope.selectedHostArray = [];
                    }
                    break;
                case 2:
                    if ($scope.countUser > 0) {
                        for (var userIndex = 0; userIndex < $scope.selectedUserArray.length; userIndex++) {
                            $scope.snmpUserGrid.dataSource.remove($scope.selectedUserArray[userIndex]);
                            $scope.snmpUserChanges = true;
                        }
                        $scope.selectedUserArray = [];
                    }
                    break;
                case 1:
                    if ($scope.countCommunity > 0) {
                        for (var communityIndex = 0; communityIndex < $scope.selectedCommunityArray.length; communityIndex++) {
                            $scope.communityGrid.dataSource.remove($scope.selectedCommunityArray[communityIndex]);
                            $scope.communityChanges = true;
                        }
                        $scope.selectedCommunityArray = [];
                    }
                    break;
            }
        };
		
		$scope.resetBtnFunction = function () {
			if ($scope.snmpTabStrip.select().index() == 1) {
				$scope.loadGridData();
				$scope.enableDeleteBtn = true;
				$scope.disableApplyButton = true;
			}
			else if ($scope.snmpTabStrip.select().index() == 2) {
				$scope.loadGridData();
				$scope.enableDeleteBtn = true;
				$scope.disableApplyButton = true;
			}
			else if ($scope.snmpTabStrip.select().index() == 3) {
				if($scope.snmpHostValidator.validate()) $scope.loadGridData();
				$scope.enableDeleteBtn = true;
				$scope.disableApplyButton = true;
			}
		
		};
	
        $scope.$watch('communityGrid', function () {
            if ($scope.communityGrid) {
               $scope.loadGridData();
            }
        });
		
		$scope.$watch('snmpUserGrid', function () {
            if ($scope.snmpUserGrid) {
               $scope.loadGridData();
            }
        });
		
		$scope.$watch('snmpHostGrid', function () {
            if ($scope.snmpHostGrid) {
               $scope.loadGridData();
            }
        });
		
		$scope.enableApplybtn1 = function(){
				$scope.snmpModel.displayAllGrid = ($scope.snmpModel.status == 'not enabled') ? translate('com_disable') : translate('com_enable');
				if($scope.snmpModel.status1 == translate('com_disable')){
					if($scope.snmpModel.status == translate('com_enable')){
						$scope.disableApplyButton = true;
					}
				}
				else if($scope.snmpModel.status1 == translate('com_enable')){
					if($scope.snmpModel.status == translate('com_disable')){
						$scope.disableApplyButton = false;
					}
				}
		}
		
		 $scope.loadGridData = function () {
			var showSNMP = requestRoutingService.getShowCmdOutput("show snmp", "snmp");
            showSNMP = showSNMP ? showSNMP.ShowSnmp.wnwebdata.entry : $scope.snmpModel;
			$scope.disableApplyButton = true;
            $scope.snmpModel.status = (showSNMP.status == 'not enabled') ? translate('com_disable') : translate('com_enable');
			$scope.snmpModel.status1 = (showSNMP.status == 'not enabled') ? translate('com_disable') : translate('com_enable');
			
            $scope.snmpModel.displayAllGrid = $scope.snmpModel.status;
            $scope.snmpModel.systemContact = showSNMP.systemContact || "";
            $scope.snmpModel.systemLocation = showSNMP.systemLocation || "";
            if (!showSNMP.globalTrap) showSNMP.globalTrap = "disabled";
            $scope.snmpModel.globalTrap = (showSNMP.globalTrap == 'disabled') ? translate('com_disable') : translate('com_enable');
            if (!showSNMP.logging) showSNMP.logging = "";
            $scope.snmpModel.logging = (showSNMP.logging == 'enabled') ? "Enabled" : "Disabled";
			
			
				var showSNMPCommunity = requestRoutingService.getShowCmdOutput("show run", "community");
				showSNMPCommunity = (showSNMPCommunity && showSNMPCommunity.ShowSnmp.SNMPCommunity.entry) ? showSNMPCommunity.ShowSnmp.SNMPCommunity.entry : [];
				$scope.communityGridData = new kendo.data.ObservableArray([]);
				if (showSNMPCommunity.length > 0) {
					for (var loopVariable = 0; loopVariable < showSNMPCommunity.length; loopVariable++) {
						var community = {
							Name: "",
							AccessMode: ""
						}
						if(showSNMPCommunity[loopVariable].Name.indexOf("ro")==-1){
							 community.Name = showSNMPCommunity[loopVariable].Name;
							 community.AccessMode = (showSNMPCommunity[loopVariable].AccessMode == "RO" ) ? "Read Only" : "Read/Write";
							 $scope.communityGridData.push(community);
						}
					   
					}
				}
				else if (showSNMPCommunity.Name) {
					var community = {
							Name: "",
							AccessMode: ""
						}
					 if(showSNMPCommunity.Name.indexOf("ro")==-1){
						community.Name = showSNMPCommunity.Name;
						community.AccessMode = (showSNMPCommunity.AccessMode == "RO" ) ? "Read Only" : "Read/Write";
						$scope.communityGridData.push(community);
					 }						
				}
				

				$scope.snmpCommunityPristineData = angular.copy($scope.communityGridData);
				$scope.communityGridDataSource = new kendo.data.DataSource({
					pageSize: 10,
					data: $scope.communityGridData
				});	
				var grid = angular.element("#communityGrid").data("kendoGrid");				
				grid.dataSource = $scope.communityGridDataSource;
				$scope.communityGridDataSource.read();
				grid.refresh();
           
            var showSNMPUser = requestRoutingService.getShowCmdOutput("show snmp user", "user");
            showSNMPUser = (showSNMPUser && showSNMPUser.ShowSnmpUser.wnwebdata.entry) ? showSNMPUser.ShowSnmpUser.wnwebdata.entry : [];
            $scope.userGridData = new kendo.data.ObservableArray([]);
			$scope.disableApplyButton = true;
            
            if(showSNMPUser.length >0) {
				for (index = 0; index < showSNMPUser.length; index++) {
					var privProtocol = showSNMPUser[index].privProtocol || "None";
					var userSnmp = {
						userName: showSNMPUser[index].userName,
						privProtocol: privProtocol,
						groupName: showSNMPUser[index].groupName,
						authProtocol: showSNMPUser[index].authProtocol,
						authPassword: "",
						privPassword: ""
					};
					$scope.userGridData.push(userSnmp);
				}
            } else if (showSNMPUser.userName) {
            	var privProtocol = showSNMPUser.privProtocol || "None";
                var userSnmp = {
                    userName: showSNMPUser.userName,
                    privProtocol: privProtocol,
                    groupName: showSNMPUser.groupName,
                    authProtocol: showSNMPUser.authProtocol,
                    authPassword: "",
                    privPassword: ""
                };
                $scope.userGridData.push(userSnmp);            	
            }
   
			$scope.snmpUserPristineData = angular.copy($scope.userGridData);
			$scope.userGridDataSource = new kendo.data.DataSource({
				pageSize: 10,
				data: $scope.userGridData
			});
				
			var grid1 = angular.element("#snmpUserGrid").data("kendoGrid");				
			grid1.dataSource = $scope.userGridDataSource;
			$scope.userGridDataSource.read();
			grid1.refresh();
			
            $scope.userGridDataSource = new kendo.data.DataSource({
                pageSize: 10,
                data: $scope.userGridData,
                schema: {
                    model: {
                        id: "userName",
                        fields: {
                            userName: {
                                validation: {
                                    required: true,
                                    namevalidation: $scope.snmpV3UsersValidations.namevalidation
                                }
                            },
                            authPassword: {},
                            groupName: {
                                validation: {
                                    required: true,
                                    groupnamevalidation: $scope.snmpV3UsersValidations.groupnamevalidation
                                }
                            },
                            privProtocol: {
                                validation: {
                                    privprotocolpasswordvalidation: $scope.snmpV3UsersValidations.privprotocolpasswordvalidation
                                }
                            },
                            authProtocol: {
                                validation: {
                                    authprotocolpasswordvalidation: $scope.snmpV3UsersValidations.authprotocolpasswordvalidation
                                }
                            }
                        }

                    }
                },
                requestStart: function (e) { //prevent grid navigation
                    if (preventUsersGridPaginationAction) {
                        e.preventDefault();
                    }
                }
            });
			
			
			var showSNMPHost = requestRoutingService.getShowCmdOutput("show snmp host", "host");
            showSNMPHost = (showSNMPHost && showSNMPHost.ShowSnmpHost.wnwebdata.entry) ? showSNMPHost.ShowSnmpHost.wnwebdata.entry : [];         
            $scope.hostGridData = new kendo.data.ObservableArray([]);
			
            if (showSNMPHost.length > 0) {
				for (index = 0; index < showSNMPHost.length; index++) {
					var securityLevel = showSNMPHost[index].securityLevel || "";
					var hostSnmp = {
						communityName: showSNMPHost[index].communityName,
						ipAddress: showSNMPHost[index].ipAddress,
						type: showSNMPHost[index].type,
						udpPort: showSNMPHost[index].udpPort,
						version: showSNMPHost[index].version,
						securityLevel: securityLevel
					};
					$scope.hostGridData.push(hostSnmp);
				}
            }else if (showSNMPHost.communityName) {
                    var securityLevel = showSNMPHost.securityLevel || "";
                    var hostSnmp = {
                        communityName: showSNMPHost.communityName,
                        ipAddress: showSNMPHost.ipAddress,
                        type: showSNMPHost.type,
                        udpPort: showSNMPHost.udpPort,
                        version: showSNMPHost.version,
						securityLevel : securityLevel
                    };
                    $scope.hostGridData.push(hostSnmp);               
            }
            $scope.snmpHostPristineData = angular.copy($scope.hostGridData);
			$scope.hostGridDataSource = new kendo.data.DataSource({
					pageSize: 10,
					data: $scope.hostGridData
				});
			
			var grid2 = angular.element("#snmpHostGrid").data("kendoGrid");				
			grid2.dataSource = $scope.hostGridDataSource;
			$scope.hostGridDataSource.read();
			grid2.refresh();
            $scope.hostGridDataSource = new kendo.data.DataSource({
                pageSize: 10,
                data: $scope.hostGridData,
                schema: {
                    model: {
                        id: "ipAddress",
                        fields: {
                            ipAddress: {
                                validation: {
                                    required: true,
                                    ipvalidation: $scope.snmpHostValidaiton.ipvalidation,
                                    reservedipvalidation: $scope.snmpHostValidaiton.reservedipvalidation
                                }
                            },
                            udpPort: {
                                validation: {
                                    udpportvalidation: $scope.snmpHostValidaiton.udpportvalidation
                                }
                            },
                            version: {},
                            type: {},
                            communityName: {
                                validation: {
                                    required: true,
                                    namevalidation: $scope.snmpHostValidaiton.namevalidation
                                }
                            },
                            securityLevel: {}
                        }
                    }
                },
                requestStart: function (e) { //prevent grid navigation
                    if (preventHostsGridPaginationAction) {
                        e.preventDefault();
                    }
                }
            });
        };
		
}]);
