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

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


        /* 
         * @returns {boolean} Return true if a cookie is found (and load it in profile) false else 
         */
        var isAlreadyLogin = function () {

            // Load cookies
            var profileInCookie = $cookies.getObject('profile');
            var tokenPart_0InCookie = $cookies.getObject('token.part_0');
            var tokenPart_1InCookie = $cookies.getObject('token.part_1');


            // Check if cookie is defined
            if (typeof profileInCookie !== 'undefined'
                    && typeof tokenPart_0InCookie !== 'undefined'
                    && typeof tokenPart_1InCookie !== 'undefined'
                    ) {

                //if(token!==null){
                // If yes, put it into variables
                angular.extend(profile, profileInCookie);
                token = tokenPart_0InCookie + tokenPart_1InCookie;
                //}

                // Return I'm Login
                return true;
            }

            // Show the login overlay
            $rootScope.$broadcast("logoutEvent");

            // Return I'm not Login
            return false;
        };



        /*
         * Destroy profile cookies
         */
        var logout = function () {
            $cookies.remove('profile');
            $cookies.remove('token.part_0');
            $cookies.remove('token.part_1');
            token = null;
            profile.username = null;
            profile.projectname = null;

            // Reload Page
            //location.reload();
            $rootScope.$broadcast("logoutEvent");

        };


        /**
         * 
         * @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) {

            // Defined return object
            var requestParserResult = {};
            requestParserResult.status = 1;
            requestParserResult.failReason = null;

            if (typeof response.data.token !== 'undefined') {
                // Set status code
                requestParserResult.status = 0;

                // Find the middle of the token to split it
                var middle = parseInt(response.data.token.length / 2);

                // Create expire date (cookie expire in 55 mins)
                var expireDate = new Date();
                expireDate.setMinutes(expireDate.getMinutes() + 55);

                // Save profile
                $cookies.putObject('profile', profile, {'expires': expireDate});
                // Save first part of token
                $cookies.putObject('token.part_0', response.data.token.substring(0, middle), {'expires': expireDate});
                // Save second part of token
                $cookies.putObject('token.part_1', response.data.token.substring(middle, response.data.token.length), {'expires': expireDate});

                // Put token in var
                token = response.data.token;

            } 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));
            });
        };





        /*
         * Get the profile
         */
        var getProfile = function () {
            return profile;
        };

        /*
         * Get the token
         */
        var getToken = function () {
            return token;
        };



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


    }]);
