/**
 Description: STP Controller
 Copyright (c) 2016 by Cisco Systems, Inc.
 All rights reserved.
 */
'use strict';
app.controller('StpCtrl', ['$scope','$rootScope','$filter', 'gridCrudService', 'dataSourceService', '$timeout', 'stpdataSourceService', 'notificationService', 'validationService','$window','dialogService','requestRoutingService',
    function ($scope,$rootScope,$filter, gridCrudService, dataSourceService, $timeout, stpdataSourceService, notificationService, validationService,$window,dialogService,requestRoutingService) {
        var trimVal=$filter('trimValue');
		var translate = $filter("translate");
	$scope.isACluster = ($rootScope.deviceInfo.stackingInfo.type == "CLUSTER");
        $scope.showPhysicalStacking = false;
        $scope.diablePortCycleButton = true;
        $scope.diableVStackApplyButton = true;
        var jumboVal = "10240";
        $scope.virtualStartCluster = "";
        var versionInfo = requestRoutingService.getShowCmdOutput("show version","overviewshVer");
        var deviceType = versionInfo.ShowVersion.name;
        /*Controller - Data & Actions For Switch Tab Starts*/
        var switchConfigDetails, switchInitialData,stackInitialData;   
        if(deviceType.indexOf("CDB")!=-1){        	
        	$scope.showSeleconDetails=true;
        	$scope.mtuSizeStatus=true;
    			$scope.showBluetoothTab=true;
    			$scope.showBluetoothDetails=true;
        }

        $scope.mtuSizeDataSource = dataSourceService.mtuSizeOptions();
        //$scope.stpStackModeType = null;
       
		    $rootScope.$watch('deviceInfo.stackingInfo', function(newVal, oldVal){
          stackInitialData = newVal.type;
        });
        $scope.initGridLoad = function () {
           switchConfigDetails = stpdataSourceService.getSwitchDetails();           
           //setting values
           $scope.switchConfigData = {
               hostName: switchConfigDetails.hostName,
               switchIp: switchConfigDetails.switchIp,
               managementVlan: switchConfigDetails.managementVlan,
               mtuSize: switchConfigDetails.mtuSize,
               subnetMask: switchConfigDetails.subnetMask,
               defaultGateway: switchConfigDetails.defaultGateway,
               switchCOAP:switchConfigDetails.switchCOAP
           };
           $scope.diableApplyButton=true;  
		   
			if(deviceType.indexOf("2960L") != -1 || deviceType.indexOf("CDB")!=-1){
				$scope.mtusizetype='1';
				$timeout(function(){        	
				   if(switchConfigDetails.mtuSize=="10240"){
					   //$scope.switchConfigData.mtuSize = "jumbo";
					   angular.element("#mtuSize").data('kendoDropDownList').value("jumbo");
				   }else{
					   //$scope.switchConfigData.mtuSize = switchConfigDetails.mtuSize;
					   angular.element("#mtuSize").data('kendoDropDownList').value(switchConfigDetails.mtuSize);
				   }
				},50);     
			}
			else{
				$scope.mtusizetype='2';
				$scope.switchConfigData.mtuSize=switchConfigDetails.mtuSize;
			}		

			if(deviceType.indexOf("CDB") != -1){
				var bluetoothData = requestRoutingService.getShowCmdOutput("show running-config | section Bluetooth");
				if(bluetoothData.indexOf("shutdown") != -1) {
					$scope.switchConfigData.bluetoothstatus = translate("toggle_off");
				}else {
					$scope.switchConfigData.bluetoothstatus = translate("toggle_on");
				}
			}
           switchInitialData = angular.copy(switchConfigDetails);
        };
        $scope.initGridLoad();
        
        //validation
        var stpValidations = angular.element("#stpForm").kendoValidator({
            rules: {
                validateip: function (input) {
                    return validationService.validateIPAddress(input);
                },
                dataspace: function (input) {
                    return validationService.validateDataSpace(input);
                },
				range: function (input) {
					if(input.val() != jumboVal){
						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;
					}
				},
				checkVlanList:function(input){
					var valMsg = input.data('checkmtusizeMsg');
					if ((valMsg==undefined)) {
						return true;
					}
					var regExp=/^[,-]+$/;
					var valStrHy=input.val().includes("--");
					var valStrCom=input.val().includes(",,");
					if(regExp.test(input.val()) || valStrHy || valStrCom || trimVal(input.val()) == "")
						return false;
					return true;
				},
				 domain: function (input) {
            var valMsg = input.data('domainMsg');
            if ((valMsg==undefined)) {
                return true;
            }
            if($scope.stpStackModeType == "CLUSTER"){
              if(input.val()==''){
                  return false;
              }else{
                /*var domain_pattern = new RegExp("((http|https)(:\/\/))?([a-zA-Z0-9]+[.]{1}){2}[a-zA-z0-9]+(\/{1}[a-zA-Z0-9]+)*\/?", "i");
                return domain_pattern.test(input.val());*/
              }
            }
              return true;
          },
			domainspace: function(input){
				  var valMsg = input.data('domainspaceMsg');
					if ((valMsg==undefined)) {
						return true;
					}
					if(/\s/g.test(input.val())){
					  return false;
					}
					return true;
				}
          }
        }).data("kendoValidator");
        
        /*Stacking Starts Here*/
		var isPhysicalStackSupported = $rootScope.deviceInfo.isPhysicalStackSupported;
        var masterId = $rootScope.deviceInfo.masterId;
        if(isPhysicalStackSupported){
          $scope.showPhysicalStacking = true;
        }
        var showClusterDetails = stpdataSourceService.getShowCluster();
        $scope.hasCluster = showClusterDetails.ClusterDetails.data != "";

        
        $scope.updateStacking = function(sType){          
          if(stackInitialData !== $scope.stpStackModeType){
            $scope.diableApplyButton = false;
          }
        }
        $scope.stpStackModeType = null;
        $scope.stackingInit = function(){
                
        
            $scope.clusterConfig();            
        };
        var oldStpStackModeType;
        $scope.loadStackingOptions = function(){
          $timeout(function(){
            if($scope.showPhysicalStacking){
              if($rootScope.deviceInfo.stackingInfo.type === "STACK"){
                $scope.stpStackModeDataSource = [{stpStackText: translate("stack_standalone"), stpStackValue:"STANDALONE"},
                      {stpStackText: translate("stack_physicalStacking"), stpStackValue:"STACK"}];  
              }else{
                $scope.stpStackModeDataSource = [{stpStackText: translate("stack_standalone"), stpStackValue:"STANDALONE"},
                        {stpStackText: translate("stack_physicalStacking"), stpStackValue:"STACK"},
                        {stpStackText: translate("stack_virtualStacking"), stpStackValue:"CLUSTER"}];
              }
            }else{
                $scope.stpStackModeDataSource = [{stpStackText: translate("stack_standalone"), stpStackValue:"STANDALONE"},
                {stpStackText: translate("stack_virtualStacking"), stpStackValue:"CLUSTER"}];
            }
            $scope.stpStackModeType = $rootScope.deviceInfo.stackingInfo.type;
            oldStpStackModeType = $scope.stpStackModeType;
            $scope.diableApplyButton = true;
          },1000);
        }
        $scope.cluster = {};
        var oldClusterDomainName;
        $scope.clusterConfig = function(){
            $scope.cluster.virtualDomainName = "";
            showClusterDetails = stpdataSourceService.getShowCluster();
            $scope.hasCluster = showClusterDetails.ClusterDetails.data != "";
            if($scope.hasCluster){
                $scope.virtualDomainName = showClusterDetails.ClusterDetails.data.domainName.replace(/"/gi, "");
                $scope.cluster.virtualDomainName = showClusterDetails.ClusterDetails.data.domainName.replace(/"/gi, "");
                oldClusterDomainName = $scope.cluster.virtualDomainName;
            }
        }
        /*Physical stacking Configuration function*/
         $scope.PhysicalStackingConfig = function(cliHostNameCmd){
            if(isPhysicalStackSupported){
				      stackingIsEdited = false;
              cliHostNameCmd+="do switch "+masterId+" stack port 1 enable \n";
              cliHostNameCmd+="do switch "+masterId+" stack port 2 enable \n";
            }
            return cliHostNameCmd;
         }
          /*Virtual stacking Configuration function*/
         $scope.virtualStackingConfig = function(cliHostNameCmd, domainNameEdited){
            if($scope.cluster.virtualDomainName && $scope.cluster.virtualDomainName !== oldClusterDomainName){
              if(!oldClusterDomainName){
                stackingIsEdited = false;

                cliHostNameCmd+="cluster run\n";
                cliHostNameCmd+="cluster enable "+$scope.cluster.virtualDomainName.replace(/ /g, '')+"\n";
              }else{
                stackingIsEdited = true;

                cliHostNameCmd+="cluster enable "+$scope.cluster.virtualDomainName.replace(/ /g, '')+"\n";
              }
            }
            return cliHostNameCmd;
          }
          /*Standalone stacking Configuration function*/
			var stackingIsEdited = false;
           $scope.standaloneConfig = function(cliHostNameCmd){
            /*show command for physcical stacking*/
            if(isPhysicalStackSupported){
              stackingIsEdited = false;
              if($scope.cluster.virtualDomainName){
                cliHostNameCmd+="no cluster enable "+$scope.cluster.virtualDomainName+"\n";
                cliHostNameCmd+="no cluster run\n";
              }
              cliHostNameCmd+="do switch "+masterId+" stack port 1 disable \n";
              cliHostNameCmd+="do switch "+masterId+" stack port 2 disable \n";
            }else{
              stackingIsEdited = false;
              if($scope.cluster.virtualDomainName){

                cliHostNameCmd+="no cluster enable "+$scope.cluster.virtualDomainName+"\n";
                cliHostNameCmd+="no cluster run\n";
              }
            }

            return cliHostNameCmd;
          }
          /*Stacking Ends Here*/

        //save switch config into device
        var redirectionState=false;
        $scope.saveSwitchConfig = function () {
        	var cliHostNameCmd="";
            if (stpValidations.validate()) {

                if ($scope.switchConfigData.hostName !== switchInitialData.hostName) {
                      cliHostNameCmd+="hostname "+$scope.switchConfigData.hostName+"\n";
                }
                if ($scope.switchConfigData.switchIp !== switchInitialData.switchIp || $scope.switchConfigData.subnetMask !== switchInitialData.subnetMask) {
                	if(deviceType.indexOf("2960X")!=-1 || deviceType.indexOf("3560CX")!=-1 || deviceType.indexOf("2960XR")!=-1 || deviceType.indexOf("2960CX")!=-1){
                		if($scope.switchConfigData.managementVlan.indexOf("gig")!=-1 || $scope.switchConfigData.managementVlan.indexOf("Gig")!=-1) {
                		    cliHostNameCmd+="int "+$scope.switchConfigData.managementVlan+"\n no switchport\n ip address "+$scope.switchConfigData.switchIp+" "+$scope.switchConfigData.subnetMask+"\n exit\n";
                		}else{
                			cliHostNameCmd+="int "+$scope.switchConfigData.managementVlan+"\n ip address "+$scope.switchConfigData.switchIp+" "+$scope.switchConfigData.subnetMask+"\n exit\n";
                		}	
                	}else{
                		 cliHostNameCmd+="int "+$scope.switchConfigData.managementVlan+"\n ip address "+$scope.switchConfigData.switchIp+" "+$scope.switchConfigData.subnetMask+"\n exit\n";
                	}                     
                }
                if ($scope.switchConfigData.managementVlan !== switchInitialData.managementVlan) {                   
                    if(switchInitialData.managementVlan.indexOf("Gig")!=-1 || $scope.switchConfigData.managementVlan.indexOf("gig")!=-1) {
                    	cliHostNameCmd+="int "+switchInitialData.managementVlan+"\n no ip address \n switchport \n exit\n";
                    } else{
                    	 cliHostNameCmd+="int "+switchInitialData.managementVlan+"\n no ip address \n exit\n";
                    }                   
                    if(deviceType.indexOf("2960X")!=-1 || deviceType.indexOf("3560CX")!=-1 || deviceType.indexOf("2960XR")!=-1 || deviceType.indexOf("2960CX")!=-1){
                		if($scope.switchConfigData.managementVlan.indexOf("gig")!=-1 || $scope.switchConfigData.managementVlan.indexOf("Gig")!=-1) {
                			cliHostNameCmd+="int "+$scope.switchConfigData.managementVlan+"\n no switchport\n ip address "+$scope.switchConfigData.switchIp+" "+$scope.switchConfigData.subnetMask+"\n exit\n";
                		}else{
                			cliHostNameCmd+="int "+$scope.switchConfigData.managementVlan+"\n ip address "+$scope.switchConfigData.switchIp+" "+$scope.switchConfigData.subnetMask+"\n exit\n";
                		}	
                	}else{
                		cliHostNameCmd+="int "+$scope.switchConfigData.managementVlan+"\n ip address "+$scope.switchConfigData.switchIp+" "+$scope.switchConfigData.subnetMask+"\n exit\n";
                	}                    
                }								
        				if ($scope.switchConfigData.mtuSize !== switchInitialData.mtuSize) {
        					if(parseInt($scope.switchConfigData.mtuSize) > 1998){
        						cliHostNameCmd+="system mtu jumbo "+$scope.switchConfigData.mtuSize+"\n";
        					}else{
        						cliHostNameCmd+="system mtu "+$scope.switchConfigData.mtuSize+"\n";
        					}					
        				}
                if ($scope.switchConfigData.defaultGateway !== switchInitialData.defaultGateway) {
                      cliHostNameCmd+="ip default-gateway "+$scope.switchConfigData.defaultGateway+"\n";
                }
                if(deviceType.indexOf("CDB")!=-1){
	                if($scope.switchConfigData.switchCOAP !== switchInitialData.switchCOAP) {
		                if ($scope.switchConfigData.switchCOAP) {
		                    cliHostNameCmd+="coap proxy \n security none \n start \n";
		                }else{
		                	cliHostNameCmd+="coap proxy \n stop \n no coap proxy \n";
		                }
	                }
                }
				        
          		 var selectedStackingOption = $filter('filter')($scope.stpStackModeDataSource, $scope.stpStackModeType);
          			if(stackInitialData !== $scope.stpStackModeType){
          			  switch(selectedStackingOption[0].stpStackText) {
          				case "Physical Stacking":
          				  cliHostNameCmd = $scope.PhysicalStackingConfig(cliHostNameCmd);
          				  break;
          				case "Virtual Stacking":
          				  cliHostNameCmd = $scope.virtualStackingConfig(cliHostNameCmd);
          				  break;
          				case "Standalone":
          				  cliHostNameCmd = $scope.standaloneConfig(cliHostNameCmd);
          				  break;
          			  }
          			}else{
                  if($scope.cluster.virtualDomainName && oldClusterDomainName !== $scope.cluster.virtualDomainName){
                    cliHostNameCmd = $scope.virtualStackingConfig(cliHostNameCmd,true);
                  }
                }
                if($scope.switchConfigData.switchIp != switchInitialData.switchIp){                  
                   var baseUrl = window.location.origin;

                   if(baseUrl.indexOf('https') > -1){
                     $window.location.href = "https://"+ $scope.switchConfigData.switchIp + "/#/switch";  
                   }else{
                     $window.location.href = "http://"+ $scope.switchConfigData.switchIp + "/#/switch";  
                   }
                }
                if(cliHostNameCmd!=""){
                  $timeout(function() {	
                    var result = requestRoutingService.getConfigCmdOutput(cliHostNameCmd);
                  	if(result=="" || result.errorResponse.indexOf("MTU will not take effect until the next reload is done")!=-1 ){
                  		notificationService.showNotification(translate('switch_success_msg'),translate('com_config_success_title'),'success');
          						if(!stackingIsEdited){
                        if(stackInitialData !== $scope.stpStackModeType){
                          location.reload();
                        }
          						}
                    }else{
                  		notificationService.showNotification(result.errorResponse,translate('com_config_fail_title'),'error');
                  	}
                  },50);
                }
          			$scope.diableApplyButton=true;
          			$scope.initGridLoad();
					$scope.clusterConfig();
                switchInitialData = angular.copy($scope.switchConfigData);
            }
        };
		
		$scope.saveBluetoothConfig = function () {
			var clibluetoothCmd="";
			if(deviceType.indexOf("CDB")!=-1){
				if ($scope.switchConfigData.bluetoothstatus === translate("toggle_on")) {
					clibluetoothCmd += "staging config bluetooth on \n";
				} else {
					clibluetoothCmd += "staging config bluetooth off \n";
				}
				 if(clibluetoothCmd!=""){
					var result = requestRoutingService.getShowCmdOutput(clibluetoothCmd);
					if(result==""){
						notificationService.showNotification(translate('switch_success_msg'),translate('com_config_success_title'),'success');
					}else{
						notificationService.showNotification(result.errorResponse,translate('com_config_fail_title'),'error');
					}
				}
				$scope.diableApplyButton = true;
			}
		};
		
		$scope.switchmtuSizeOnchange = function(){
			$scope.diableApplyButton = false;
		};
        //cancel the changes
        $scope.cancelSwitchConfig = function () {
        	 $scope.diableApplyButton=true;
        	 $scope.switchConfigData.hostName=switchInitialData.hostName;
        	 $scope.switchConfigData.switchIp=switchInitialData.switchIp;
        	 $scope.switchConfigData.managementVlan=switchInitialData.managementVlan;
        	 $scope.switchConfigData.mtuSize=switchInitialData.mtuSize;
        	 $scope.switchConfigData.subnetMask=switchInitialData.subnetMask;
        	 $scope.switchConfigData.defaultGateway=switchInitialData.defaultGateway; 
        	 $scope.switchConfigData.switchCOAP=switchInitialData.switchCOAP; 
        	 $scope.initGridLoad();
           $scope.clusterConfig();
           $scope.stpStackModeType = oldStpStackModeType; 
        };
        
        
        $scope.commonConfirmationSwitch = function() {
            $scope.dlgSwitch = dialogService.dialog({
                content : translate("msg_redirect_confirmation")+" "+$scope.switchConfigData.switchIp,
                title : translate("msg_redirect_confirmation_window"),
                messageType : "confirm",
                actionButtons : [{
                    text : translate("com_ok"),
                    callback : "pageRedirection"
                }, {
                    text : translate("com_cancel")
                }]
            });
        };
        $scope.$on("pageRedirection", function(event, data) {
          $scope.dlgSwitch.data("kendoWindow").close();
            $timeout(function(){
              $scope.saveSwitchConfig();
            },50);
        });
        $scope.redirection= function(){
           if($scope.switchConfigData.switchIp != switchInitialData.switchIp){
        	   redirectionState=true;
        	   $scope.commonConfirmationSwitch();        	   
           }else{
        	   redirectionState=false; 
        	   $scope.saveSwitchConfig();
           }               
        };
      

        
        /*Controller - Data & Actions For Switch Tab Ends*/
        

        /*Controller - Data & Actions For STP Tab Starts*/
        /*Default Values*/
        var stpDefaultModeType = "rapid-pvst";
        /*To Identify Edited filed*/
        $scope.gridEdited = false;
        $scope.stpModeEdited = false;
        /*Display Values*/
        $scope.stpModeType=null;
        $scope.stpGridValues = [];
        $scope.stpPriorityOptions = dataSourceService.stpPriorityOptions();
        $scope.stpModeDataSource = dataSourceService.stpModeOptions();
		   
        /*To Identify Actual Edit*/
        $scope.stpModeModel = null;
        $scope.editedVlanListValues = [];

        /*Enable and Disabling Cancel & Apply Buttons*/
        $scope.disableApplyButton = function () {
            return ($scope.stpModeEdited || $scope.gridEdited) ? false : true;
        };
        $scope.disableCancelButton = function () {
            return ($scope.stpModeEdited || $scope.gridEdited) ? false : true;
        };
       
        
        

        $scope.stpGridValues = stpdataSourceService.getVlanData();
        var deviceData = angular.copy($scope.stpGridValues);

        /*Kendo Grid-Data Values*/
        var hdrTmpbridgePriorityNum=translate("stp_bridgepriority") + " <tooltip helptext='" + translate("help_STP_bridge_priority_number") +"' position='top'></tooltip>";
        $scope.stpInstanceGridOptions = {
            editable: true,
            filterable: {
                extra : false,
                messages: {
                    isTrue: translate("com_enable"),
                    isFalse: translate("com_disable"),
                    info: translate("com_page_dropDowntext"),
		            filter: translate("com_btn_filter"),
		            clear: translate("com_btn_clear")
                },
                operators : {
                    string : {
                        eq : translate("com_is_equal"),
                        neq : translate("com_isnot_equal")
                    }
                }
            },
            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: 5
            },
            scrollable: true,
            selectable: true,
            columns: [{
                field: "vlanId",
                title: translate("stp_vlanid")
            }, {
                field: "vlanName",
                title: translate("stp_vlanname")
            }, {
                field: "hasSpanningTree",
                title: translate("stp_spanningtree"),
                template:'<span >#= hasSpanningTree === true ? "'+translate("com_enable")+'": "'+translate("com_disable")+'" #</span>'
            }, {
            	 field: "bridgePriorityNumber",
                 title: translate("stp_bridgepriority"),
                 headerTemplate :hdrTmpbridgePriorityNum,
                 template: "#=bridgePriorityNumber#",
                 editor: function (container, options) {
                     var inlineEditSpanningTreeFlag = !options.model.hasSpanningTree;
                     container.append(angular.element('<select ng-disabled="' + inlineEditSpanningTreeFlag +
                     '" kendo-drop-down-list="stpPriority" name="stpPriority" id="stpPriority" k-data-source="stpPriorityOptions" k-data-text-field="\'name\'" k-data-value-field="\'value\'" data-bind="value:'
                     + options.field + '" ></select>'));
                 }
            }]
        };
        $scope.stpInstancedataSource = kendoGridObject($scope.stpGridValues);
        /*STP Mode Select*/
        $scope.updateStpMode = function () {        	
            if ( ($scope.stpModeModel) && ($scope.stpModeModel !== $scope.stpModeType)) {
                $scope.stpModeEdited = true;
            } else {
                $scope.stpModeEdited = false;
            }
        };
        /*Apply Button Click*/
        $scope.apply = function () {
        	var resultResponse=null;
            if ($scope.stpModeEdited) {
            	var stpCliCommand="spanning-tree mode ";
                stpCliCommand=stpCliCommand+$scope.stpModeType;
                resultResponse=requestRoutingService.getConfigCmdOutput(stpCliCommand);
                $timeout(function () {
                    $scope.stpModeType = stpdataSourceService.getStpModeType() ? stpdataSourceService.getStpModeType() : stpDefaultModeType;
                    $scope.stpModeModel = angular.copy($scope.stpModeType);
                }, 50);
                $scope.stpModeEdited = false;
            }
            if ($scope.gridEdited) {
                var editedObject = $scope.editedVlanListValues;
                resultResponse = stpdataSourceService.sendingVlanDataToDevice(editedObject);
                var updatedData = stpdataSourceService.getVlanData();
                var dataSource = kendoGridObject(updatedData);
                var grid = angular.element('#stpInstanceGrid').data('kendoGrid');
                dataSource.read();
                grid.setDataSource(dataSource);
                deviceData = angular.copy(dataSource);    
                
                $scope.gridEdited = false;
            }
            if(resultResponse==""){
        		notificationService.showNotification(translate('switch_success_msg'),translate('com_config_success_title'),'success');
        	}else{
        		notificationService.showNotification(resultResponse.errorResponse,translate('com_config_fail_title'),'error');
        	}
        };
        /*Cancel Button Click*/
        $scope.cancel = function () {
            if ($scope.stpModeEdited) {
                $scope.stpModeType = $scope.stpModeModel;
                $scope.stpModeEdited = false;
            }
            if ($scope.gridEdited) {
            	var updatedData = stpdataSourceService.getVlanData();
                var dataSource = kendoGridObject(updatedData);

                var grid = angular.element('#stpInstanceGrid').data('kendoGrid');
                dataSource.read();
                grid.setDataSource(dataSource);
                $scope.gridEdited = false;
            }
        };

        function kendoGridObject(dataValues) {
            var newOject = new kendo.data.DataSource({
                pageSize: 10,
                data: dataValues,
                batch: true,
                change: function (e) {
                    var dataList = this.data();
                    var editedVlanList = [];
                    for (var index = 0; index < dataList.length; index++) {
                        if (dataList[index].hasOwnProperty('dirty') && dataList[index].dirty == true) {
                            var editedObj = {};
                            editedObj["vlanId"] = dataList[index].vlanId;
                            editedObj["vlanName"] = dataList[index].vlanName;
                            editedObj["hasSpanningTree"] = dataList[index].hasSpanningTree;
                            editedObj["bridgePriorityNumber"] = dataList[index].bridgePriorityNumber;
                            editedVlanList.push(editedObj);
                        }
                    }
                    if (editedVlanList.length > 0) {
                        $scope.editedVlanListValues = editedVlanList;
                        $scope.gridEdited = true;
                    }
                },
                schema: {
                    model: {
                        id: "vlanId",
                        fields: {
                            vlanId: {
                                editable: false,
                                nullable: true
                            },
                            vlanName: {
                                editable: false,
                                nullable: true
                            },
                            hasSpanningTree: {
                                type: "boolean"
                            },
                            bridgePriorityNumber: {
                                
                            }
                        }
                    }
                }
            });
            return newOject;
        };
        
        $timeout(function () {        	
            $scope.stpModeType = stpdataSourceService.getStpModeType() ? stpdataSourceService.getStpModeType() : stpDefaultModeType;
            $scope.stpModeModel = angular.copy($scope.stpModeType);
        }, 1000);
        
        /*Controller - Data & Actions For STP Tab Ends*/

    }
]);
