app.controller('loginCtrl',
	
function ($scope,$http,$cookies, $location,$timeout, utilsSvc, userService, UserManager) {
	
	$scope.user = {username:'', password:'', userProfile:'', userDescription: ''};
	
	
	//$scope.UserManager = new UserManager();
	
	$scope.login = function() {
		userService.clearFilter();
		try {
			UserManager.Login($scope.user).$promise.then(function(data) {
				$cookies.put('user', JSON.stringify(data));
				
				$scope.clearLocalStorage();
				$location.path('/');
			}, function(error) {
				$cookies.remove('user');
				if (error.status=404)
					utilsSvc.show("Autenticazione fallita");
				else if (error.status=401)
					utilsSvc.show("E' necessario effettuare l'autenticazione");
				else
					utilsSvc.show("Errore " + error.status+ " durante la comunicazione con il server: " + error.statusText);  
			});
		} catch(Ex) {
			Console.log(Ex);
		}
	}
	
	$scope.clearLocalStorage = function(){
		localStorage.removeItem('filter');
		localStorage.removeItem('filterDistinte');
		localStorage.removeItem('filterDistinteAttivo');
		localStorage.removeItem('filterDistinteSelectedIndex');
	}	
	
    $scope.checkCredential = function () {
        userService.login($scope.user, $location)
        	.success(function(response) {
        		if(response != null && response!="") {
                    console.log("login successful.");
	                // todo: setta il cookie di autenticazione
	                $cookies.put("user", JSON.stringify(response));
	                var path = $location.$$protocol+'://'+$location.$$host+':'+$location.$$port+'/sicura';
	                window.location = path;
	                
	                //$location.path('/');
	            } else {
	                console.log("login failed.");
	                $cookies.remove("user");
	                utilsSvc.showMessage('Nome utente o password errati');
;	            }        		
        })
        .error(function(err) {
        	console.log("Error occurred during login.");
        	utilsSvc.showMessage('Nome utente o password errati');
        });
        	
       
    }
    
    $scope.getGroups = function(){
    	if ($scope.user.username != '' && $scope.user.password != '') {
    		
    		UserManager.AutenticationGroups($scope.user,
    				function(data){
    					console.log(data);
    					$scope.profiles = data;
					}
    		);
    	}
    }
    
    $scope.init = function() {
    	$timeout(function() {
    		// 	Fix for password field not updating label correctly in Chrome
//    		document.querySelector("input[type=password]").focus();
//    		document.querySelector("input[type=password]").value = " ";
//    		document.querySelector("input[type=password]").value = "";
//    		document.querySelector("input[type=password]").blur();
//    		document.querySelector("#username").select();
//    		document.querySelector("#username").focus();

    	},0,false);
    	
    	UserManager.GetUserInfo().
    		$promise.then(function(data){
    			$scope.user.username = data.login;
    			$scope.user.password = '*';
    			$scope.profiles = data.gruppi;
    		});
    }
    
    $scope.init();
}
);