import { Marker } from '../toubiz-map/data/marker';
import { initializeMap } from './map/map-factory';

/**
 * @typedef {object} StandaloneMap~Marker
 * @property {number} latitude
 * @property {number} longitude
 * @property {string} tour
 * @property {string} iconUrl
 * @property {number} iconWidth
 * @property {number} iconHeight
 */

/**
 * @typedef {object} StandaloneMap~Options
 * @property {StandaloneMap~Marker[]} markers
 * @property {string} mapType
 * @property {AbstractMapWithMarkers~Options} [map = {}]
 */

/**
 * Static map: Displays a static map until the user clicks on it at which point a
 * dynamic map is being loaded.
 */
export class StandaloneMap {

    /**
     * @param {HTMLElement} node
     * @param {StandaloneMap~Options} settings
     */
    constructor (node, settings) {
        /** @private {HTMLElement} */
        this.node = node;

        /** @private {StaticMap~Options} */
        this.settings = settings;

        this.initialize();
    }

    async initialize() {
        const map = await initializeMap(this.settings.mapType, this.node, this.settings.map);
        const markers = this.getMarkers();
        await map.render(markers);

        const tours = markers.filter(marker => !!marker.tour);
        const centerOnTour = tours.length === 1 && map.drawTourOntoMap;

        if (map.drawTourOntoMap) {
            for (const tour of tours) {
                map.drawTourOntoMap(tour, centerOnTour);
            }
        }

        if (!centerOnTour) {
            map.centerMapOnMarkers(markers);
        }
    }

    /**
     * @private
     * @returns {Marker[]}
     */
    getMarkers() {
        const id = Math.random().toString(26).substr(2);
        return this.settings.markers.map((data, index) => {
            const marker = new Marker(data.id || `standalone-${id}-${index}`);
            marker.coordinates = {
                latitude: parseFloat(data.latitude),
                longitude: parseFloat(data.longitude),
            };
            if (data.tour) {
                marker.tour = { polygon: JSON.parse(data.tour) };
            }
            if (data.iconUrl) {
                const width = data.iconWidth || 35;
                const height = data.iconHeight || 50;
                marker.style = {
                    width,
                    height,
                    offsetX: width / 2,
                    offsetY: height,
                    iconUrl: data.iconUrl,
                };
            }
            return marker;
        });
    }

}
