import { Controller } from "@hotwired/stimulus";
import { GisState, getMarkerByCoords } from "../state.js";

export default class extends Controller {
    static values = {
        'coords': String,
        'group': String,
        'id': String,
    };

    END_ZOOM = 19;
    // Animation breaks automatic tooltip opening...
    mapAnimate = {
        animate: true,
        duration: 1,
        easeLinearity: 0.25
    };

    /**
     * @param {Event} event 
     */
    go() {
        let map = GisState.map;
        const coords = this.coordsValue.split(' ');

        map.setView(
            coords,
            this.END_ZOOM,
            {animate: false}
        );

        let marker = this.getMarker(map, coords);
        // DEBUG for sites
        if (this.groupValue) marker = getMarkerByCoords(coords, this.groupValue);
        marker?.openTooltip();
    }
    /**
     * @param {L.Map} map
     * @param {Array<String>} coords
     * @returns {L.Marker}
     */
    getMarker(map, coords) {
        let marker;
        map.eachLayer(layer => {
            if (layer instanceof L.Marker) {
                const latLng = layer.getLatLng();
                const {lat, lng} = latLng;
                if (lat === Number(coords[0]) && lng === Number(coords[1])) {
                    marker = layer;
                    return;
                }
            }
        });

        return marker;
    }
}
