// Global Leaflet and ATON

import {config} from '../config.js';
import Scene from './scene.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);

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

        L.marker(marker.coords).addTo(map)
            .bindPopup(popup)
            .openPopup();
        
    });

    AppState.map = map;
}

export default Map;