/**
 Description: Controller for User Administration
 Copyright (c) 2016 by Cisco Systems, Inc.
 All rights reserved.
 */
app.controller('UserAdministrationCtrl', ['$scope','$timeout', '$filter', 'gridCrudService','requestRoutingService','dataSourceService','dialogService','notificationService',
	function($scope,$timeout, $filter, gridCrudService,requestRoutingService,dataSourceService,dialogService,notificationService) {
		var translate = $filter("translate");
		var trimVal=$filter('trimValue');
		$scope.userAdministration = {
				userName : "",
				privilege : "",
				password : ""
		};	
		
	
		var userValidations = $("#userForm").kendoValidator({
				rules : {
					maximum : function(input) {
						var minValue = input.data('maximum');
						if (minValue)
							return input.val().length < Number(minValue);
						return true;
					},
					matches : function(input) {
						var matches = input.data('matches');
						if (matches) {
							return (input.val() === $scope.userAdministration.password);
						}
						return true;
					},
					check:function(input){
						var msg = input.data('checkMsg');
						if ((msg==undefined)) {
							return true;
						}
						var regExp=/^[A-Za-z][A-Za-z0-9]*$/;
						if(regExp.test(input.val()))
							return true;
						return false;
					},
					existing : function(input) {
						if (!input.data('existingMsg'))
							return true;
						var val = input.val();
						if (!$scope.userData || $scope.userData.length <= 0)
							return true;
						for (var i = 0; i < $scope.userData.length; i++) {
							if ($scope.userData[i]["userName"] == val) {
								return false;
							}
						}
						return true;
					},
					minimum : function(input) {
						var minValue = input.data('minimum');
						if (minValue)
							return input.val().length > Number(minValue);
						return true;
					}
			}
		}).data("kendoValidator");
		
		$scope.disableUserName = true;
		$scope.disableDelete = true;
		$scope.disableApplyButton = true;
		$scope.disableSubmit = true;
		$scope.privilegeOptions = dataSourceService.privilegeOptions();
				
		$scope.userAdministration = angular.copy($scope.userAdministration);
		$scope.userDirty="";
		var userConfigCLI="";
		var editUserData = function(){
			$("#userForm  span.k-tooltip-validation").hide();
			var selected = this.dataItem(this.select());
			$timeout(function(){$scope.userShowEditSection = true;});
			$scope.userAdministration.userName = selected.userName;
			$scope.userAdministration.privilege = selected.privilege;
			$scope.userAdministration.password = selected.password;
			$scope.userAdministration.confirmPassword = selected.password;
			$scope.userDirty=selected.dirty;
			$scope.disableUserName = true;
			$scope.disableDelete = false;
		};

		$scope.saveUserData = function(){
			if (userValidations.validate()) { 				
			$scope.disableApplyButton = false;
			if($scope.userDirty){  //add function
				$scope.userGrid.dataSource.add({"userName": $scope.userAdministration.userName,"privilege": $scope.userAdministration.privilege,"password": $scope.userAdministration.password});
			}else{ //for edit
				var selectedItem = $scope.userGrid.dataItem($scope.userGrid.select());
				selectedItem.userName = $scope.userAdministration.userName;
				selectedItem.privilege = $scope.userAdministration.privilege;
				selectedItem.password = $scope.userAdministration.password;
			}
			userConfigCLI += "username "+$scope.userAdministration.userName+" privilege "+$scope.userAdministration.privilege+" password 0 "+$scope.userAdministration.password+"\n";						
			$scope.reset();
		 }
		}
		
		
		$scope.deleteData = function(popup) {
			var selectedItem = $scope.userGrid.dataItem($scope.userGrid.select());
			$scope.userGrid.dataSource.remove(selectedItem);
			userConfigCLI += "no username "+selectedItem.userName+" privilege "+selectedItem.privilege+" password 0 "+selectedItem.password+"\n";
			$scope.disableApplyButton = false;
			popup.close();

		}
		
		$scope.addUser = function() {
			$scope.userAdministration = angular.copy($scope.userAdministration);
			$scope.userShowEditSection = true;
			$scope.disableUserName = false;
			$scope.disableDelete = true;
			$scope.userAdministration.userName = "";
			$scope.userAdministration.privilege = "0";
			$scope.userAdministration.password = "";
			$scope.userAdministration.confirmPassword = "";	
			$scope.userDirty=true;
			$("#userForm  span.k-tooltip-validation").hide();
		};
		
		$scope.applyUser=function(){
			var result = requestRoutingService.getConfigCmdOutput(userConfigCLI);
			if(result==""){
				notificationService.showNotification(translate('user_success_msg'),translate('com_config_success_title'),'success');
			}else{
				notificationService.showNotification(result.errorResponse,translate('com_config_fail_title'),'error');
			}
		}
		
		$scope.deleteConfirmation = function() {
			$scope.commonConfirmationUser('delete');
		};

		$scope.commonConfirmationUser = function() {
			$scope.dlgUser = dialogService.dialog({
				content : translate("msg_delete_confirmation"),
				title : translate("msg_delete_confirmation_window"),
				messageType : "confirm",
				actionButtons : [{
					text : translate("com_ok"),
					callback : "userDeleteConfirmation"
				}, {
					text : translate("com_cancel")
				}]
			});
		};

		$scope.$on("userDeleteConfirmation", function(event, data) {
			$scope.disableApplyButton = false;
			$scope.deleteData($scope.dlgUser.data("kendoWindow"));
		});
		
		//Showing configured username list in the grid
		var showUserList =requestRoutingService.getShowCmdOutput("show running-config aaa username","userNew");
		if(showUserList.ShowUsers.Users.entry){
			showUserList=showUserList.ShowUsers.Users.entry;
			if (typeof showUserList == "object" && !showUserList.length)
				showUserList = [showUserList];
				$scope.showUserList = $.map(showUserList, function(value, index) {
				return [value];
		    });
		}
		
		$scope.userData = new kendo.data.ObservableArray(showUserList)
		$scope.userDataSource = new kendo.data.DataSource({
			pageSize : 10,
			data : $scope.userData
		});

		$scope.reset = function() {
			$scope.userAdministration.userName = "";
			$scope.userAdministration.privilege = "0";
			$scope.userAdministration.password = "";
			$scope.userAdministration.confirmPassword = "";		
			$scope.userShowEditSection = false;
		};
		
		//Kendo Grid options
		$scope.userGridOptions = {
			editable : false,
			filterable : true,
			sortable : true,
			change : editUserData ,
			pageable: {
				  messages: {
					  display: translate("com_page_display"), //{0} is the index of the first record on the page, {1} - index of the last record on the page, {2} is the total amount of records
					  empty: translate("com_page_empty"),
					  page: translate("com_page_pagetext"),
					  of:translate("com_page_of"),  //{0} is total amount of pages
					  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")
				   },
				   pageSizes : gridCrudService.grid_page_sizes,
				   refresh : true,
				   buttonCount : 5
			},
			filterable : {
				extra : false,
				operators : {
					string : {
						eq : translate("com_is_equal"),
                        neq : translate("com_isnot_equal")
					}
				},
				messages : {
		            info: translate("com_page_dropDowntext"),
		            filter: translate("com_btn_filter"),
		            clear: translate("com_btn_clear")
		        }

			},
			scrollable : false,
			selectable : true,
			
			columns : [
			{
				field : "userName",
				editable : "false",
				title : translate("user_administration_name"),
				width : 25
			}, {
				field : "privilege",
				editable : "false",
				title : translate("user_administration_priv"),
				width : 25
			}, {
				field : "password",
				hidden : "true"
			}]
		};		
		
	}]);
