angular
        .module('carfriend')
        .factory('UsersService', usersService);

function usersService(Backand, $http, $q) {
    var baseUrl = '/1/objects/';
    var object = 'users/';

    var services = {
        post: post,
        getAll: getAll,
        fetch: fetch,
        update: update,
        fetchByUsername: fetchByUsername,
        emailSetting:emailSetting
    };
    return services;

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

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

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

    function post(message) {
        return $http.post(getUrl(), message);
    }
    ;
    
    function update(id, data) {
        return $http.put(getUrlForId(id), data);
    }
    ;

    function getAll() {
        return $http.get(baseUrl);
    }
    ;

    function fetch(userId) {
        var deffered = $q.defer();
        $http({
            method: 'GET',
            url: getUrlForId(userId),
            params: {
                level: 1,
                deep: true,
                filter: JSON.stringify([{
                        "fieldName": "id",
                        "operator": "in",
                        "value": userId
                    }])
            }
        }).then(function (response) {
            deffered.resolve(response)
        }, function (err) {
            deffered.reject(err);
        });
        return deffered.promise;
    }
    ;

    function fetchByUsername(username) {
        var deffered = $q.defer();
        $http({
            method: 'GET',
            url: getUrl(),
            params: {
                filter: JSON.stringify([{
                        "fieldName": "username",
                        "operator": "equals",
                        "value": username
                    }])
            }
        }).then(function (response) {
            deffered.resolve(response)
        }, function (err) {
            deffered.reject(err);
        });
        return deffered.promise
    }
    ;
    function emailSetting(userid, value) {
        var deffered = $q.defer();
        $http({
            method: 'PUT',
            url: getUrlForId(userid),
            data: {
                emailNotifications: value
            }
        }).then(function (response) {
            deffered.resolve(response);
        }, function (error) {
            deffered.reject(error);
        });
        return deffered.promise;
    }
    ;
}