angular
        .module('carfriend')
        .factory('AuthService', authService);

function authService(Backand, $http, $q, $state) {
    var baseUrl = '/1/objects/';
    var object = 'users/';
    var currentUser = {};
    
    var services = {
        fetch: fetch,
        loadUserDetails: loadUserDetails,
        signIn: signIn,
        signUp: signUp,
        signout: signout,
        findUserByUsername:findUserByUsername,
        getCurrentUserInfo: getCurrentUserInfo,
        getUser: getUser
    };
    
    return services;

    ///////////////

    function getUrl() {
        return Backand.getApiUrl() + baseUrl + object;
    }
    ;

    function getUrlForId(id) {
        return getUrl() + id;
    }
    ;

    function fetch(id) {
        return $http.get(getUrlForId(id));
    }
    ;
    
    function loadUserDetails() {
        currentUser.username = Backand.getUsername();
        if (currentUser.username) {
            var deffered = $q.defer();
            $http({
                method: 'GET',
                url: getUrl(),
                params: {
                    filter: JSON.stringify([{
                            fieldName: "email",
                            operator: "equals",
                            value: currentUser.username
                        }])
                }
            }).then(function (response) {
                if(response && response.data && response.data.data.length === 1)
                    deffered.resolve(currentUser.details = response.data.data[0]);
            }, function (error) {
                deffered.reject(error);
            });
            return deffered.promise;
        } else {
            return $state.go('login');
        }
    }
    ;

    function getCurrentUserInfo() {
        return loadUserDetails().then(function (response) {
            return response;
        });
    }
    ;

    function signIn(username, password) {
        return Backand.signin(username, password);
    }
    ;

    function signUp(firstName, lastName, email, password, again, parameters) {
         console.log("signUp");
        return Backand.signup(firstName, lastName, email, password, again, parameters);
    }
    ;


    function signout() {
        return  Backand.signout().then(function () {
            angular.copy({}, currentUser);
        });
    }
    ;

    function getUser() {
        return currentUser;
    }
    ;

    function findUserByUsername(username) {
        var deffered = $q.defer();
        $http({
            method: 'GET',
            url: getUrl(),
            headers: {
                'AnonymousToken': '8f432fe2-33c1-4bef-9f4b-9c5502c8f3b1'
            },
            params: {
                filter: JSON.stringify([{
                        "fieldName": "username",
                        "operator": "equals",
                        "value": username
                    }])
            }
        }).then(function (response) {
            deffered.resolve(response);
        }, function (error) {
            deffered.reject(error);
        });
        return deffered.promise;
    }
    ;

}
;

