mainApp.factory('Identity',[ '$http', '$cookies', function($http, $cookies){

	/* Create profile structure to store informations
	 * about current session
	 */
    var profile={};
    profile.username=null;
    profile.projectname=null;
	profile.token=null;


	/**
	 * Save profile in cookies 
	 */
	var saveCookieForSession=function(){
		$cookies.putObject('profile', 5);
	};


	/* 
	 * @returns {boolean} Return true if a cookie is found (and load it in profile) false else 
	 */
	var isAlreadyLogin=function(){
		var profileInCookie=$cookies.getObject('profile');
		console.log(profileInCookie);
		
		if(typeof profileInCookie !== 'undefined'){
			angular.extend(profile, profileInCookie);
			return true;
		}

		return false;
	}

	/*
	 * Destroy profile cookies
	 */
	var logout=function(){
		$cookies.remove('profile');
	}

	
	/**
	 * 
	 * @param {string} response The response to parse
	 * @param {boolean} to check if the request is send or not
	 * @returns {requestParserResult} Formated data
	 */
	var parseLoginAnswer=function(response, failedToSendRequest){
		

		var requestParserResult={};
		requestParserResult.status=1;
		requestParserResult.failReason=null;

		if (typeof response.data.token !== 'undefined') {
			requestParserResult.status=0;
			profile.token=response.data.token;
			saveCookieForSession();
		}
		else if(failedToSendRequest){
			requestParserResult.failReason="Failed to send request";
		}
		else{
			requestParserResult.failReason="Please check your username, password and project name !";
		}
		
		return requestParserResult;
	};


	
	/**
	 * Function to connect to OpenStack
	 * 
	 * @param {object} $http Angular $http service
	 * @param {string} username The user name
	 * @param {string} password The user password
	 * @param {string} projectname The user project name
	 * @param {function} function to call when data is avalaible
	 */
	var login=function(username, password,projectname, callback){    
		
		// Set profile information (early)
		profile.username=username;
		profile.projectname=projectname;
		
		var result=$http.post('../server/index.php',
						  $.param({"task" : "Authenticate", "user" : username, "password" : password, "project" : projectname}));  

		// Wait and handle the response
        result.then(function (response){
			callback(parseLoginAnswer(response), false);
        },function(response){
			callback(parseLoginAnswer(response), true)
        });		
	};	



	// Return services objects
	return {
		login: login,
		profile: profile,
		isAlreadyLogin: isAlreadyLogin,
		logout:logout
	};

	
}]);