import { Controller } from "@hotwired/stimulus";
import { GisState } from "../state.js";
import GIS from "../gis.js";

export default class extends Controller {
    static targets = [
        'sites',
        'findings',
        'notconserved',
        'prehist',
    ];

    static values = {
        'id': Number,
        'type': String,
    };

    async toggleCartography() {
        const map = GisState.map;
        const id = this.idValue;

        let currentLayer = await GIS.getImageOverlay(id);
        let hasLayer = false;

        map.eachLayer(function (layer) {
            if (layer.options.label === currentLayer.options.label) {
                hasLayer |= true;
                currentLayer = layer;
            }
        });

        if (!hasLayer) currentLayer.addTo(map);
        else map.removeLayer(currentLayer);
    }

    toggleCadastral() {
        const map = GisState.map;
        const wms = GisState.cartography.cadastral;

        if (!map.hasLayer(wms)) map.addLayer(wms);
        else map.removeLayer(wms);
    }

    /**
     * @todo Use Stimulus values?
     * @param {Event} event 
     */
    toggle(event) {
        let map = GisState.map;
        let target = event.currentTarget;
        const id = target.parentElement.getAttribute('data-id');
        this.toggleIcon(event.currentTarget);

        let group = GisState.layers[id];

        if (map.hasLayer(group)) {
            map.removeLayer(group);
            target.title = "Mostra";
        }
        else {
            map.addLayer(group);
            target.title = "Nascondi";
        }
    }
    /**
     * Toggle visibility icon...
     * @param {HTMLElement} target
     */
    toggleIcon(target) {
        const icon = target.firstElementChild;
        const className = icon.className;
        icon.className = className.includes('slash') ?
            className.replace('-slash', '') :
            className.replace('eye', 'eye-slash');
    }
}

