(function () {

    angular.module('ctfApp').factory('AuthenticationService', ['AppSettings', 'Base64', '$http', '$cookieStore', '$rootScope',
        function (AppSettings, Base64, $http, $cookieStore, $rootScope) {

            return {

                /**
                 * Login user.
                 * @param username
                 * @param password
                 * @param callback
                 */
                login: function (username, password, callback) {

                    $http.get('http://' + username + ":" + password + "@" + AppSettings.apiAddress + '/whoami', {
                        headers: {'Authorization': 'Basic ' + Base64.encode(username + ':' + password)}
                    })
                        .then(function (response) {
                            console.debug("RESPONSE", response);
                            response.team = response.data.teamName;
                            callback(response);
                        }, function(response) {
                            callback(response);
                        });

                },

                /**
                 * Logout.
                 * @param callback
                 */
                logout: function (callback) {

                    $http.get('http://' + 'askdjfadsf' + ':' + 'adsfasskdjfadsf' + '@' + AppSettings.apiAddress + '/whoami', {
                        headers: {'Authorization': 'Basic ' + Base64.encode('askdjfadsf' + ':' + 'adsfasskdjfadsf')}
                    }).then(function(response){
                        this.clearCredentials();
                        callback(response);
                    }.bind(this), function(response){
                        this.clearCredentials();
                        callback(response);
                    }.bind(this));


                },

                /**
                 * Saves credentials to cookies and ensures that they are appended to every request.
                 * @param username
                 * @param password
                 */
                setCredentials: function (username, password) {

                    var authdata = Base64.encode(username + ':' + password);

                    $rootScope.globals = {
                        currentUser: {
                            username: username,
                            authdata: authdata
                        }
                    };

                    $http.defaults.headers.common.Authorization = 'Basic ' + authdata;
                    $cookieStore.put('globals', $rootScope.globals);

                },

                /**
                 * Clears credentials saved in cookies.
                 */
                clearCredentials: function () {

                    $rootScope.globals = {};
                    $cookieStore.remove('globals');
                    $http.defaults.headers.common.Authorization = 'Basic ';

                }

            };
        }
    ]);
})();