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

export default class extends Controller {
    static values = {
        'coords': String,
        'group': String,
        'id': String,
    };
    
    uiModals = {
        sites: '#site-data',
        notConserved: '#not-conser-data',
        finding: '#finding-data',
        prehist: '#prehist-data',
        reuse: '#reuse-data',
    };

    END_ZOOM = 19;

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

        map.setView(
            coords,
            event.params?.zoom ? event.params.zoom : this.END_ZOOM,
            {animate: false}
        );

        let marker = this.getMarker(map, coords);
        marker?.openTooltip();

        return marker;
    }
    /**
     * Go to a marker location on the map
     * and open its modal
     */
    goAndOpen() {
        const marker = this.go();
        const selector = this.uiModals[this.groupValue];
        const data = marker.options.data;

        switch(this.groupValue) {
            case 'sites':
                UI.openSiteModal(data, selector);
                break;
            case 'notConserved':
                UI.openNotConserModal(data, selector);
                break;
            case 'finding':
                UI.openFindingModal(data, selector);
                break;
            case 'prehist':
                UI.openPrehistModal(data, selector);
                break;
            case 'reuse':
                UI.openReuseModal(data, selector);
                break;
            default:
                console.log('Cannot open modal...');
                break;
        }
    }
    /**
     * @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;
    }
}
