(function () {
    'use strict';

    angular
        .module('contestacaoApp')
        .directive('mapsDirective', mapsDirective);

    mapsDirective.$inject = ['__env', 'configuracoesService', 'mapsSingletonService'];

    /* @ngInject */
    function mapsDirective(__env, configuracoesService, mapsSingletonService) {
        return {
            restrict: 'A',
            replace: false,
            link: link,
            scope: false
        };

        function link(scope, element) {
            configuracoesService.carregarConfiguracoesGerais()
                .then(successConfiguracoesGerais)
                .catch(error => console.error(error));

            function successConfiguracoesGerais(result) {
                const map = mapsSingletonService.getMap();
                let params = {};
                let mapType = null;

                if (result.data.UsarGoogleParaGeoCode) {
                    params = {
                        apiKey: result.data.ChaveMapa,
                        gestureHandling: false,
                        options: {
                            streetViewControl: true
                        }
                    };
                    mapType = InlogMaps.MapType.Google;
                } else {
                    params = {
                        scriptsDependencies: [
                            'angular/Contestacao/app/scripts/utils/leaflet.polylineDecorator.js'
                        ]
                    };
                    mapType = InlogMaps.MapType.Leaflet;
                }

                mapsSingletonService.setMapType(mapType);

                map.initialize(mapType, params, element[0].id)
                    .then(() => scope.vm.inicializarController());
            }
        }
    }
})();
