import { getCurrentUserLocation } from '../../utilities';
import { GeolocationMarker } from './leaflet-geolocation-marker';

export class GeolocationHandler {

    constructor (L, map, options) {
        this.L = L;
        this.map = map;
        this.enableControl();

        if (!options.waitForUserIntent) {
            this.onGeolocationIntent();
        }
    }

    onGeolocationIntent() {
        getCurrentUserLocation()
            .then(position => {
                this.position = position;
                this.map.panTo(position);
                this.drawLocationMarker();
            })
            .catch(console.warn);
    }

    enableControl() {
        this.L.Control.Geolocation = this.L.Control.extend({
            onAdd: () => {
                const geolocationControlDiv = document.createElement('div');
                geolocationControlDiv.className =
                    'tb-map-custom-control tb-map-custom-control--leaflet leaflet-bar leaflet-control';
                geolocationControlDiv.title = 'Map auf aktuellem Standort zentrieren';
                geolocationControlDiv.innerHTML = `
                    <svg class="c-icon tb-map-custom-control__icon">
                        <use xlink:href="#tb-map-geolocation"></use>
                    </svg>
                `;

                geolocationControlDiv.addEventListener('click', () => this.onGeolocationIntent());
                return geolocationControlDiv;
            },
            onRemove: () => {},
        });

        this.L.control.geolocation = new this.L.Control.Geolocation({ position: 'topright' });
        this.L.control.geolocation.addTo(this.map);
    }

    async drawLocationMarker() {
        if (!this.marker) {
            this.marker = new GeolocationMarker(this.L, this.position, this.map);
        }
    }

}
