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
            `));
        }

        if (options.width > 640 || options.height > 640) {
            console.warn(stripMultilineIndention(`
                ## Toubiz Map Configuration Warning
                Google static maps does not support dimensions over 640x640 but you
                have supplied ${options.width}x${options.height}
            `));
        }

        return options;
    }

    imageUrl(markers, size) {
        const urlParameters = [
            `zoom=${Math.round(this.options.zoom * 18 / 100)}`,
            `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('|')}`);
            }
        }

        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('|')}`;
    }
}
