var module = angular.module('usersUI', []);

function usersCtrl($scope, $http) {
		
	$scope.users = [];
	
	$scope.listUsers = function() {
		showSpinner();
		$http.get('users.get')
        .success(
            function(data) {
            	$scope.users = data;
            	hideSpinner();
            }
        ).error(
            function() {
            	show_notification("error", "Error accessing user permission levels");
            	hideSpinner();
            }
        );
	}
	
	$scope.addUser = function(user) {
		if (user) {
			user = user.trim();
			if (user) {
				var lngt = $scope.users.length;
				for(i=0; i < lngt; i++) {
					if ($scope.users[i].id == user) {
						show_notification("error", "User " + user +  " is already present");
						return;
					}
				}
				$scope.users.push( {'id' : user, 'permissionLevels': [] });
				show_notification("info", "Added user: " + user);
			}
		}
	}
	
	$scope.dropUser = function(i) {
		user = $scope.users[i].id;
		$scope.users.splice(i, 1);
		show_notification("info", "User " + user + " deleted");
	}
	
	$scope.updateUser = function(i, level, b) {
		user = $scope.users[i];
		pos = user.permissionLevels.indexOf(level);
		if (b) {
			if (pos < 0) user.permissionLevels.push(level);
		} else {
			if (pos >= 0) user.permissionLevels.splice(pos, 1); 
		}
		//show_notification("info", "User " + user.id + " updated");
	}
	
	$scope.saveUsers = function() {
		showSpinner();
		
        $http.defaults.headers.post["Content-Type"] = "application/json";
        
		$http.post('saveusers.do', $scope.users )
		.success(
				function(data) {
					show_notification("info", "Users saved correctly");
					hideSpinner();
				}
		).error(
			function() {
				show_notification("error", "Error saving users");
				hideSpinner();
			}
		);
	}
	
	initSpinner();
	
	$scope.listUsers();
	
}