angular
    .module('carfriend')
    .factory('ChatService', chatService);

function chatService(Backand, $http, $q, $filter) {
    var baseUrl = '/1/objects/';
    var messagesObject = 'messages/';
    var chatObject = 'chats/'
    
    
    var services = {
        post: post,
        getAll: getAll,
        fetch: fetch,
        createChat: createChat,
        findOne: findOne,
        removeChat: removeChat,
        getMessages: getMessages
    };
    return services;

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

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

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

    function removeChat(chatId) {
        return $http.delete(getUrlForId(chatId, chatObject));
     }
    

    function createChat(chat) {
        console.log("chat.service - creating chat", chat);
        var deffered = $q.defer();
        $http({
            method: 'POST',
            url: getUrl(chatObject) + '??returnObject=true',
            data: {
                user1: chat.user1,
                user2: chat.user2,
                created: $filter('date')(new Date(), 'yyyy-MM-dd HH:mm:ss')
            }
        }).then(function (response) {
            deffered.resolve(response);
        }, function (error) {
            deffered.reject(error);
        });
        return deffered.promise;
    }
    ;
    
    function findOne(user1, user2) {
        var deffered = $q.defer();
        $http({
            method: 'GET',
            url: getUrl(chatObject), // + '??returnObject=true',
            params: {
                deep: true,
                filter: JSON.stringify([{
                        "fieldName": "user1",
                        "operator": "in",
                        "value": user1
                    }, {
                        "fieldName": "user2",
                        "operator": "in",
                        "value": user2
                    }])
            }
        }).then(function (response) {
            deffered.resolve(response);
        }, function (error) {
            deffered.reject(error);
        })
        return deffered.promise;
    }
    ;
    
    function post(message, email) {
        var deffered = $q.defer();
        $http({
            method: 'POST',
            url: getUrl(messagesObject),
            params: {
                deep: false,
                relatedObjects: false,
                parameters: {
                    email: email,
                }
            },
            data: message
        }).then(function (response) {
            deffered.resolve(response);

        }, function (error) {
            deffered.reject(error);
        })
        return deffered.promise;
    }
    ;

    function getAll() {
        var deffered = $q.defer()
        $http({
            method: 'GET',
            url: getUrl(chatObject),
            params: {
                relatedObjects: false,
                deep: false
            }
        }).then(function (data) {
            deffered.resolve(data);
        }, function (err) {
            deffered.reject(err);
        });
        return deffered.promise;
    }
    ;

    function getMessages(chatID, kolko) {
        var deffered = $q.defer()
        $http({
            method: 'GET',
            url: getUrl(messagesObject),
            params: {
                pageSize: kolko,
                exclude: 'metadata',
                sort: [{    
                        "fieldName": "datetime",    
                        "order": "desc"  
                    }],
                filter: JSON.stringify([{
                        "fieldName": "chats",
                        "operator": "in",
                        "value": chatID
                    }])
            }
        }).then(function (data) {
            deffered.resolve(data);
        }, function (err) {
            deffered.reject(err);
        });
        return deffered.promise;
    }
    ;

    function fetch(chatId, kolko) {
        var deffered = $q.defer()
        $http({
            method: 'GET',
            url: getUrlForId(chatId, chatObject),
            params: {
                pageSize: kolko
            }
        }).then(function (data) {
            deffered.resolve(data);
        }, function (err) {
            deffered.reject(err);
        });
        return deffered.promise;
    }
    ;
}