app.factory('AuthenticationService', ['$rootScope', '$http', function ($rootScope, $http) {
    var AuthenticationService = {};

    $rootScope.user = {};
    $rootScope.user.loggedIn = false;
    AuthenticationService.ensureLoggedIn = function($q, $http, $location, $rootScope) {
        var deferred = $q.defer();

        $http.get('/loggedin')
            .success(function(data) {
                $rootScope.user.loggedIn = data.loggedin;
                if (data.loggedin) {
                    console.log('AuthenticationService.ensureLoggedIn : you are logged in');
                    deferred.resolve();
                }
                else {
                    console.log('AuthenticationService.ensureLoggedIn : you are logged out');
                    deferred.reject();
                    $location.url('/login');
                }
            });
        return deferred.promise;
    };

    AuthenticationService.isLoggedIn = function () {
        return $rootScope.user.loggedIn;
    };

    AuthenticationService.isLoggedOut = function () {
        return !$rootScope.user.loggedIn;
    };

    AuthenticationService.login = function (email, password, callback) {

        $http
            .post('/login', { email: email, password: password })
            .success(function (response) {
                console.log('AuthenticationService.login : success! you are now logged in');
                $rootScope.user.loggedIn = true;
                callback(null);
            })
            .error(function (err) {
                $rootScope.user.loggedIn = false;
                callback(err);
            });
    };

    AuthenticationService.register = function (userData, callback) {

        $http
            .post('/register', {
                firstName: userData.firstName,
                lastName: userData.lastName,
                email: userData.email,
                password: userData.password
            })
            .success(function () {
                callback(null);
            })
            .error(function (err) {
                callback(err);
            });
    };

    AuthenticationService.logout = function (callback) {

        $http
            .post('/logout', {})
            .success(function (response) {
                console.log('AuthenticationService.logout : success! you are now logged out');
                $rootScope.user.loggedIn = false;
                $rootScope.$broadcast('logout');
                callback(null);
            })
            .error(function (err) {
                callback(err);
            });
    };

    return AuthenticationService;

}]);
