/**
	 * Google Maps
	 */
import IGDATAPOOLFE from '@dp/ig_datapool_fe.js';

const mapPlugin = {
    initFields(form) {
        this.init(form);
    },
    init(form) {
        this.form = form;

        const mapInputs = form.querySelectorAll('.dp-map-input');

        mapInputs.forEach((el) => {
            const lat = parseFloat(el.dataset.lat);
            const lng = parseFloat(el.dataset.lng);

            const hasMarker = el.dataset.hasmarker;
            const autosearch = el.dataset.autosearch;

            const mapOptions = {
                center: { lat, lng },
                zoom: Number(el.dataset.zoom),
                panControl: el.dataset.pancontrol === 'true',
                zoomControl: el.dataset.zoomcontrol === 'true',
                scaleControl: el.dataset.scalecontrol === 'true',
                mapTypeControl: el.dataset.maptypecontrol === 'true',
                streetViewControl: el.dataset.streetviewcontrol === 'true',
                overviewMapControl: el.dataset.overviewmapcontrol === 'true',
                scrollwheel: el.dataset.scrollwheel === 'true'
            };

            const mapElement = el.querySelector('.gmap');

            const map = new google.maps.Map(mapElement, mapOptions);

            const marker = new google.maps.Marker({
                position: new google.maps.LatLng(lat, lng),
                draggable: true
            });

            if (hasMarker == 1) {
                marker.setMap(map);
            }

            // map click
            google.maps.event.addListener(map, 'click', function (event) {
                marker.setPosition(event.latLng);
                marker.setMap(map);
            });

            // marker move
            google.maps.event.addListener(marker, 'position_changed', function () {
                const hiddenInput = el.querySelector('input[type="hidden"]');
                if (hiddenInput) {
                    hiddenInput.value =
                        this.getPosition().lat() + ',' + this.getPosition().lng();
                }
            });

            // custom events (replace jQuery .on)
            const resizeHandler = () => {
                const center = map.getCenter();
                google.maps.event.trigger(map, "resize");
                map.setCenter(center);
            };

            form.addEventListener('tab_changed', resizeHandler);
            form.addEventListener('smartresize', resizeHandler);

            const geocoder = new google.maps.Geocoder();

            const geoInput = el.querySelector('.geoCoderWrapper input');
            const geoButton = el.querySelector('.geoCoderWrapper button');

            const geoSearch = () => {
                geocoder.geocode(
                    { address: geoInput.value },
                    function (results, status) {
                        if (status === google.maps.GeocoderStatus.OK) {
                            map.setCenter(results[0].geometry.location);
                            marker.setPosition(results[0].geometry.location);
                            marker.setMap(map);
                        }
                    }
                );
            };

            // button click
            geoButton?.addEventListener('click', geoSearch);

            // enter key
            geoInput?.addEventListener('keydown', (e) => {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    geoSearch();
                }
            });

            // autosearch
            if (autosearch) {
                const autoElements = document.querySelectorAll(autosearch);

                const updateAutoSearch = () => {
                    const values = [];

                    autoElements.forEach((input) => {
                        if (input.value) values.push(input.value);
                    });

                    geoInput.value = values.join(', ');
                };

                autoElements.forEach((input, index) => {
                    input.addEventListener('change', updateAutoSearch);

                    // trigger initial update
                    if (index === autoElements.length - 1) {
                        updateAutoSearch();
                        input.addEventListener('change', geoSearch);
                    }
                });
            }
        });
    };
};

IGDATAPOOLFE.addPlugin('map', mapPlugin);
export default mapPlugin;
