(function () {
    'use strict';

    angular
        .module('mdFuncionalidadesMapa')
        .factory('geocodeReverse', geocodeReverse);

    geocodeReverse.$inject = ['inconformidadesService']

    function geocodeReverse(inconformidadesService) {
        function GetAddress(latLng, usarGeoGoogle, callSuccess, callError) {
            if (usarGeoGoogle) {
                var geocoder = new google.maps.Geocoder();
                geocoder.geocode({ 'latLng': latLng }, function (results, status) {
                    if (status !== google.maps.GeocoderStatus.OK) {
                        callError(status);
                    }
                    // This is checking to see if the Geoeode Status is OK before proceeding
                    if (status == google.maps.GeocoderStatus.OK) {
                        let address = (results[0].formatted_address);
                        if (results[0].address_components && results[0].address_components.find(a => a.types.some(t => t.indexOf('route') > -1)))
                            address = results[0].address_components.find(a => a.types.some(t => t.indexOf('route') > -1)).long_name.toUpperCase()
                        callSuccess(address);
                    }
                });
            } else {
                inconformidadesService.BuscarEndereco(latLng).then((data) => callSuccess(data.data.Rua));
            }
        }
        return { GetAddress: GetAddress };
    }
})();
