angular
        .module('carfriend')
        .factory('CleaningService', cleaningService);

function cleaningService(Backand, $http, $q, $filter) {
    var baseUrl = '/1/objects/';
    var object = 'cleaning/';

    var services = {
        checkCleaningToday: checkCleaningToday,
        checkLocality: checkLocality,
        checkStreet: checkStreet
    };
    return services;

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

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

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

    function checkCleaningToday(street, locality) {
        var deffered = $q.defer();
        $http({
            method: 'GET',
            url: getUrl(),
            params: {
                filter: JSON.stringify([{
                        "fieldName": "route",
                        "operator": "equals",
                        "value": street
                    }, {
                        "fieldName": "locality",
                        "operator": "equals",
                        "value": locality
                    }, {
                        "fieldName": "date",
                        "operator": "equals",
                        "value": $filter('date')(new Date(), 'MM/dd/yyyy')
                    }])
            }
        }).then(function (response) {
            deffered.resolve(response);
        }, function (err) {
            deffered.reject(err);
        });
        return deffered.promise;
    };
    
    function checkLocality(locality) {
        var deffered = $q.defer();
        $http({
            method: 'GET',
            url: getUrl(),
            params: {
                filter: JSON.stringify([{
                        "fieldName": "locality",
                        "operator": "equals",
                        "value": locality
                    }])
            }
        }).then(function (response) {
            deffered.resolve(response);
        }, function (err) {
            deffered.reject(err);
        });
        return deffered.promise;
    };
    
      function checkStreet(street) {
        var deffered = $q.defer();
        $http({
            method: 'GET',
            url: getUrl(),
            params: {
                filter: JSON.stringify([{
                        "fieldName": "route",
                        "operator": "equals",
                        "value": street
                    }])
            }
        }).then(function (response) {
            deffered.resolve(response);
        }, function (err) {
            deffered.reject(err);
        });
        return deffered.promise;
    };
}
;

