<template>
    <l-map
        id="the-map"
        ref="myMap"
        :zoom="zoom"
        :min-zoom="min_zoom"
        :max-zoom="max_zoom"
        :center="center"
        :options="{zoomControl: false}"
        @click="onClick"
    >
        <l-tile-layer
            :url="url"
            :attribution="attribution"
        ></l-tile-layer>

        <l-marker
            v-for="loc in store.locations"
            :lat-lng="loc.coordinates"
        >
            <l-popup>
                {{ loc.label }}
            </l-popup>
        </l-marker>

        <l-control-zoom position="topright"></l-control-zoom>

        <Sidebar></Sidebar>
    </l-map>
</template>

<script>
import { LPopup, LControl, LControlZoom, LMap, LTileLayer, LMarker } from 'vue2-leaflet';
import * as L from 'leaflet';

import store from '../store';

import Sidebar from './Sidebar';

const TILE_URL = 'https://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png';
const ATTRIBUTION = 'Carte données &copy; <a href="https://osm.org/copyright/">OpenStreetMap (ODbL)</a> / fond OSM-FR (CC-by-SA), <a href="https://www.data.gouv.fr/fr/datasets/points-dinterets-openstreetmap/">POI: OpenStreetMap (ODbL)</a>, <a href="https://www.data.gouv.fr/fr/datasets/base-d-adresses-nationale-ouverte-bano/">adresses BANO (ODbL)</a>, <a href="https://github.com/addok/addok">geocodeur addok</a>';

const MIN_ZOOM = 6;
const MAX_ZOOM = 18;
const INITIAL_ZOOM = 14;

export default {
    name: 'fullmap',

    components: {
        LMap,
        LTileLayer,
        LMarker,
        LControlZoom,
        LControl,
        LPopup,
        Sidebar,
    },

    data() {
        let lat = this.$route.params.lat;
        let lng = this.$route.params.lng;

        return {
            center: L.latLng(lat, lng),
            zoom: INITIAL_ZOOM,
            min_zoom: MIN_ZOOM,
            max_zoom: MAX_ZOOM,
            url: TILE_URL,
            attribution: ATTRIBUTION,
            store,
        };
    },

    methods: {
        onClick(event) {
            let {lat, lng} = event.latlng;
            this.$router.replace(`/${lat}/${lng}`);
            this.$refs.myMap.mapObject.panTo(event.latlng);
        },
    },

    mounted() {
        this.store.setMapObject(this.$refs.myMap.mapObject);
    },

    watch: {
        $route(to, from) {
            if (to.name === 'position') {
                let {lat, lng} = to.params;
                this.$refs.myMap.mapObject.panTo({ lat, lng });
            }
        },
    }
};
</script>

<style src="leaflet/dist/leaflet.css"></style>

<style scoped>
#the-map {
    width: 100%;
    height: 100vh;
}
</style>
