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

export class GoogleMapsStatic extends AbstractStaticMap {

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

        options.googleMapStyle = options.googleMapStyle || [ 'roadmap' ];
        if (!options.googleMapsApiKey) {
            console.warn(stripMultilineIndention(`
                ## Toubiz Map Configuration Warning
                No google maps api key supplied
            `));
        }

        return options;
    }

    imageUrl(markers, size) {
        const urlParameters = [
            `size=${size.width}x${size.height}`,
            'scale=2',
            `maptype=${this.options.googleMapStyle[0]}`,
        ];

        if (this.options.googleMapsApiKey) {
            urlParameters.push(`key=${this.options.googleMapsApiKey}`);
        }

        for (const marker of markers) {
            urlParameters.push(this.markerUrlSegment(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:red|${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://maps.googleapis.com/maps/api/staticmap?${urlParameters.join('&')}`;
    }

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