// Global Leaflet and ATON

import {config} from '../config.js';
import AppState from './state.js';

const Map = {};

Map.domParser = new DOMParser;

Map.init = function(mapContainerId) {
    let baseMap = new L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxNativeZoom : config.map.maxZoom,
        maxZoom: config.map.maxZoom,
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    });

    // Mappa centrata su Roma...
    let map = L.map(mapContainerId, {
        //attributionControl: false,
        minZoom: config.map.minZoom
    }).setView(config.map.center, config.map.initialZoom);

    baseMap.addTo(map);

    //const markerIcon = L.divIcon({className: 'bi bi-bank text-large'});

    config.markers.forEach(marker => {
        const popup = this.domParser.parseFromString(marker.popup, 'text/html')
            .querySelector('div');
        popup.querySelector('button').onclick = () => {
            this.goToScene(marker.uri);
            map.getContainer().classList.toggle('d-none');
        };

        L.marker(marker.coords,).addTo(map)
            .bindPopup(popup, {autoClose:false, /*closeOnClick:false*/})
            .togglePopup();
    });

    AppState.map = map;
}

/**
 * 
 * @param {String} uri The scene's absolute URI (from config)
 */
Map.goToScene = function (uri) {
    location.href = uri;
}

export default Map;