import { Controller } from '@hotwired/stimulus';
import L from "leaflet";
        

/**
 */
export default class extends Controller {
    static targets = [ 'map', 'modal', 'coords', 'name', 'container'];

    initialize() {
        this.setIcon();
        this.coordinates = this.coordsTarget.textContent.split(', ');

        const map = L.map(this.mapTarget.id, {
            attributionControl: false,
            minZoom: 5,
        }).setView(this.coordinates, 17);

        map.crs = L.CRS.EPSG4326;

        this.map = map;
        this.addOsMap();
        this.addMarker();
    }

    open() {
        this.modalTarget.classList.add('is-active');
        let map = this.map;

        map.invalidateSize();
    }

    close() {
        this.modalTarget.classList.remove('is-active');
    }

    addOsMap() {
        let osmap = new L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
            maxNativeZoom : 22,
            maxZoom: 22,
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        });

        osmap.addTo(this.map);
    }

    setIcon() {
        this.icon = L.icon({
            iconUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-icon.png',
            shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-shadow.png'
        });
    }

    addMarker() {
        L.marker(
            this.coordinates,
            {icon: this.icon}
        )
        .bindTooltip(this.nameTarget.textContent)
        .openTooltip()
        .addTo(this.map);
    }
}
