import { Leaflet } from '../leaflet/leaflet';
import { stripMultilineIndention } from '../../../common/string-utilities';
import { loadMapToolkit } from '../../utilities';

/**
 * Map toolkit implementation.
 * As map toolkit is just a wrapper around leaflet with some custom default values preset
 * this implementation just extends the Leaflet implementation and swaps out the map
 * initialization with the one provided by MTK.
 */
export class MapToolkit extends Leaflet {

    /**
     * @returns {Promise}
     * @protected
     */
    async initializeMap() {
        this.MTK = await loadMapToolkit(this.options.toursprungApiKey, this.options.googleMapsApiKey);
        this.L = window.L;

        return new Promise(resolve => {
            this.MTK.createMap(this.node, this.mapToolkitConfiguration(), map => {
                resolve(map.leaflet);
            });
        });
    }

    /**
     * @private
     * @returns {object}
     */
    mapToolkitConfiguration() {
        const center = this.coordinatesToLatLng(this.options.center);
        center.lat = center.lat || 47.980870;
        center.lng = center.lng || 7.820810;

        const config = {
            leaflet: {  zoomControl: false },
            map: {
                minZoom: 0,
                maxZoom: 18,
                location: {
                    center,
                    zoom: this.options.zoom * 18 / 100,
                },
                mapType: this.options.toursprungMapStyle[0].identifier,
                mapTypes: { },
                controls: [ ],
            },
        };

        for (const style of this.options.toursprungMapStyle) {
            config.map.mapTypes[style.identifier] = style.identifier;
        }

        if (this.options.toursprungMapStyle.length > 1) {
            config.map.controls.push(this.MTK.Control.MapTypes);
        }

        return config;
    }

    prepareOptions (options) {
        options = super.prepareOptions(options);
        options.toursprungMapStyle = options.toursprungMapStyle || [ { identifier: 'terrain_v2' } ];
        if (!options.toursprungApiKey) {
            console.warn(stripMultilineIndention(`
                ## Toubiz Map Configuration Warning
                Using toursprung map without API key. Please provide a valid API key.
            `));
            options.toursprungApiKey = 'sandbox';
        }
        return options;
    }

}
