angular
        .module('carfriend')
        .factory('CarService', carService);

function carService(Backand, $http, $q) {
    var baseUrl = '/1/objects/';
    var object = 'cars/';
    var car = {};

    var services = {
        all: all,
        fetch: fetch,
        findCarByEvc: findCarByEvc,
        getUserByCarId: getUserByCarId,
        getUserCars: getUserCars,
        search: search,
        create: create,
        update: update,
        delete: del,
        getCar: getCar
    };

    return services;

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

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

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

    function all(userid) {
        return $http({
            method: 'GET',
            url: getUrl(),
            params: {
                filter: JSON.stringify([{
                        "fieldName": "user",
                        "operator": "in",
                        "value": userid
                    }])
            }
        }).then(function (response) {
            if (response.data && response.data.data) {
                car = response.data.data[0];
                return car;
            }
        });
    }
    ;

    function getCar() {
        return car;
    }

    function fetch(id) {
        return $http.get(getUrlForId(id));
    }
    ;

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

    function getUserByCarId(carid) {
        return $http({
            method: 'GET',
            url: getUrl(),
            params: {
                filter: JSON.stringify([{
                        "fieldName": "id",
                        "operator": "equals",
                        "value": carid
                    }]),
                deep: true
            }
        }).then(function (response) {
            if (response.data && response.data.data && response.data.data.length === 1) {
                return response.data.data[0].__metadata.descriptives.user.label;
            } else {
                return null;
            }
        });
    }
    ;

    function getUserCars(userId) {
        return $http({
            method: 'GET',
            url: getUrl(),
            params: {
                filter: JSON.stringify([{
                        "fieldName": "user",
                        "operator": "in",
                        "value": userId
                    }])
            }
        }).then(function (response) {
            if (response.data && response.data.data) {
                return response.data.data[0];
            }
        });
    }

    function search(evc, color) {
        return findCarByEvc(evc).then(function (found) {
            console.log(found)
            if (found.data.data.length > 0) {
                return $http({
                    method: 'GET',
                    url: getUrl(),
                    params: {
                        filter: JSON.stringify([{
                                "fieldName": "evidenceNumber",
                                "operator": "equals",
                                "value": evc
                            }, {
                                "fieldName": "color",
                                "operator": "equals",
                                "value": color
                            }])
                    }
                }).then(function (response) {
                    if (response.data && response.data.data && response.data.data.length === 1) {
                        return response.data.data[0];
                    } else {
                        return "no match";
                    }
                }, function (error) {
                    console.log(error);
                });
            } else {
                //this evidence number is not registered. Notification is possible to send althought
                return "no registered";
            }
        });
    }
    ;

    function create(object) {
        return $http.post(getUrl(), object);
    }
    ;

    function update(id, object) {
        return $http.put(getUrlForId(id), object);
    }
    ;

    function del(id) {
        return $http.delete(getUrlForId(id));
    }
    ;
}
;

