import { AbstractStaticMap } from './abstract-static-map';
import { stripMultilineIndention } from '../../../common/string-utilities';

export class MapToolkitStatic extends AbstractStaticMap {

    prepareOptions (options) {
        options = super.prepareOptions(options);

        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';
        }

        if (options.staticMarkerIconUrl && options.staticMarkerIconUrl.indexOf('https://') === 0) {
            console.warn(stripMultilineIndention(`
                ## Toubiz Map Configuration Warning
                Toursprung static map icons must be available using http://, not https://.
                You supplied ${options.staticMarkerIconUrl}
            `));
        }

        return options;
    }

    imageUrl (markers, size) {
        const urlParameters = [
            'maptype=terrain-v2',
            `size=${size.width}x${size.height}`,
            'factor=2',
        ];

        for (const marker of markers) {
            urlParameters.push(this.markerQueryStringPart(marker.coordinates.latitude, marker.coordinates.longitude));

            if (marker.tour && marker.tour.polygon) {
                const polygon = marker.tour.polygon.map(([ latitude, longitude ]) => `${latitude},${longitude}`);
                urlParameters.push(`path=color:FF000088|points:${polygon.join('|')}`);
            }
        }

        // Only honor zoom if there is a single marker without a tour.
        // If there is more, then do not specify zoom (=autozoom)
        if (markers.length === 1 && !markers[0].tour) {
            urlParameters.push(`zoom=${Math.round(this.options.zoom * 18 / 100)}`);
        }

        return `https://staticmap.maptoolkit.net/?${urlParameters.join('&')}`;
    }

    markerQueryStringPart(latitude, longitude) {
        const parts = [ `center:${latitude},${longitude}` ];
        if (this.options.staticMarkerIconUrl) {
            parts.push(`icon:${encodeURIComponent(this.options.staticMarkerIconUrl)}`);
        }
        return `marker=${parts.join('|')}`;
    }

}
