angular
        .module('carfriend')
        .factory('geolocationService', geolocationService);

function geolocationService($q, $timeout, $cordovaGeolocation) {
    var currentPosition;
    var posOptions = {timeout: 10000, enableHighAccuracy: false};
    var geocoder = new google.maps.Geocoder;
    
    var services = {
        getCurrentPosition: getCurrentPosition,
        getCurrentLocation: getCurrentLocation,
        isStreetExist: isStreetExist
    };

    return services;

    /////////

    function getCurrentPosition() {
        console.log("get current position");
        if (!currentPosition) {
            var deffered = $q.defer();
            $cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) {
                console.log("position");
                deffered.resolve(currentPosition = position);
                $timeout(function () {
                    currentPosition = undefined;
                }, 10000);
            }, function (err) {
                console.log("EERR,", err);
                deffered.reject(err);
            });
            return deffered.promise;
        }
        return $q.when(currentPosition);
    }
    ;

    function getCurrentLocation(position) {
        console.log(position)
        var deferred = $q.defer();
        var latlng = new google.maps.LatLng(position.latitude, position.longitude);
        geocoder.geocode({'location': latlng}, function (results, status) {
            if (status === google.maps.GeocoderStatus.OK) {
                deferred.resolve(results);
            } else {
                deferred.reject("Couldn't find that address! Google Maps says: " + status);
            }
        });
        return deferred.promise;
    }
    ;
    
    function isStreetExist(street) {
        console.log(street);
        var deferred = $q.defer();
        geocoder.geocode({componentRestrictions: {route: street}}, function (results, status) {
                deferred.resolve(results);
        });
        return deferred.promise;
    }
    ;
}
;

