import { getCurrentUserLocation } from '../../utilities';

export class GeolocationHandler {

    constructor (map, options) {
        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() {
        const geolocationControlDiv = document.createElement('div');
        geolocationControlDiv.className = 'tb-map-custom-control tb-map-custom-control--google';
        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>
        `;

        google.maps.event.addDomListener(geolocationControlDiv, 'click', () => this.onGeolocationIntent());
        this.map.controls[google.maps.ControlPosition.RIGHT_TOP].push(geolocationControlDiv);
    }

    async drawLocationMarker() {
        if (!this.marker) {
            const { default: GeolocationMarker } = await import(
                /* webpackChunkName: "google-geolocation-marker" */
                'exports-loader?GeolocationMarker!./google-geolocation-marker'
            );
            this.marker = new GeolocationMarker(this.position, this.map);
        }
    }

}
