import { loadOutdoorActive } from '../toubiz-poi/outdoor-active-api';
import { ensureLoadingPromiseOnlyExistsOnce, loadScript, loadStyle } from '../common/load-utilities';

/**
 * @param {Marker} marker
 * @private
 */
export function trackOutdoorActiveIfConfigured(marker) {
    if (!marker.outdoorActiveTrackingId) {
        return;
    }

    loadOutdoorActive().then(oax => {
        oax.api.trackTeaser(marker.outdoorActiveTrackingId);
    });
}

/**
 * @param {string} toursprungApiKey
 * @param {string} googleMapsApiKey
 * @returns {Promise}
 */
export function loadMapToolkit(toursprungApiKey, googleMapsApiKey) {
    const version = '8.9';
    // TODO Load jQuery locally instead of from CDN
    const scriptLoading = loadScript('https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js', 'mtk-jquery')
        .then(() =>  loadScript(`https://static.maptoolkit.net/api/v${version}/mtk.de.js`, 'mtk-script'));
    const styleLoading = loadStyle(`https://static.maptoolkit.net/api/v${version}/mtk.css`, 'mtk-style');

    // MTK also provides leaflet
    ensureLoadingPromiseOnlyExistsOnce('leaflet', () => scriptLoading.then(() => window.L));

    return Promise.all([ scriptLoading, styleLoading ]).then(() => {
        const initConfig = { apiKey: toursprungApiKey };
        if (googleMapsApiKey) {
            initConfig.googleApiKey = googleMapsApiKey;
        }
        window.MTK.init(initConfig);
        return window.MTK;
    });
}

/**
 * @returns {Promise}
 */
export function loadLeaflet() {
    return ensureLoadingPromiseOnlyExistsOnce('leaflet', () => {
        import(/* webpackChunkName: "leaflet" */ 'leaflet/dist/leaflet.css');
        return import(/* webpackChunkName: "leaflet" */ 'leaflet');
    });
}

/**
 * @returns {Promise}
 */
export function loadLeafletClusterer() {
    return ensureLoadingPromiseOnlyExistsOnce('leaflet-marker-cluster', () => {
        import(/* webpackChunkName: "leaflet-cluster" */ 'leaflet.markercluster/dist/MarkerCluster.css');
        import(/* webpackChunkName: "leaflet-cluster" */ 'leaflet.markercluster/dist/MarkerCluster.Default.css');
        return import(/* webpackChunkName: "leaflet-cluster" */ 'imports-loader?L=>window.L!leaflet.markercluster');
    });
}
