(function () {
    'use strict';

    angular
        .module('setoresApp')
        .service('mapsSingletonService', mapsSingletonService);

    mapsSingletonService.$inject = ['__env'];

    function mapsSingletonService(__env) {
        const _currentMap = new InlogMaps.Map;
        let _mapType = InlogMaps.MapType.Leaflet;

        function getIconSize(url) {
            return new Promise((resolve, reject) => {
                const img = new Image();
                img.onload = function () {
                    const size = [this.width, this.height];
                    resolve(size);
                }
                img.onerror = (err) => {
                    console.warn('Image not found: ' + url);
                    resolve(undefined);
                };
                img.src = url;
            });
        };

        function buscarGeoCodeReverso(latLng) {
            return new Promise((resolve, reject) => {
                if (_mapType === InlogMaps.MapType.Google) {
                    let geocoder = new google.maps.Geocoder();
                    geocoder.geocode({
                        'location': new google.maps.LatLng(latLng[0], latLng[1])
                    }, (results, status) => {
                        if (status === google.maps.GeocoderStatus.OK) {
                            return results[0] ? resolve(results[0].formatted_address) :
                                reject('Houve um erro');
                        }
                    });
                } else {
                    $.ajax({
                        url: `${__env.baseUrl}/Comum/Comum/BuscarEndereco`,
                        data: {
                            lat: latLng[0],
                            lng: latLng[1]
                        },
                        dataType: 'json',
                        type: 'GET'
                    }).done(data => resolve(data.EnderecoCompleto))
                        .fail(err => reject(err));
                }
            });
        }

        return {
            setMapType: (mapType) => _mapType = mapType,
            getMapType: () => _mapType,
            getMap: () => _currentMap,
            getIconSize: getIconSize,
            buscarGeoCodeReverso: buscarGeoCodeReverso
        };
    }
})();
