import { loadOutdoorActiveForTracking } 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;
    }

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

/**
 * @param {string} toursprungApiKey
 * @param {string} googleMapsApiKey
 * @returns {Promise}
 */
export function loadMapToolkit(toursprungApiKey, googleMapsApiKey) {
    const version = '8.10';
    const scriptLoading = loadScript(
        '/_Resources/Static/Packages/Newland.Toubiz.Map.Neos/Static/Scripts/jquery-2.2.4.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');
        import(/* webpackChunkName: "leaflet-fullscreen" */ 'leaflet-fullscreen/dist/leaflet.fullscreen.css');
        import(/* webpackChunkName: "leaflet-fullscreen" */ 'leaflet-fullscreen');
        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');
    });
}

/**
 * @returns {Promise}
 */
export const getCurrentUserLocation = () => new Promise((resolve, reject) => {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(position => {
            resolve({
                lat: position.coords.latitude,
                lng: position.coords.longitude,
            });
        }, () => {
            reject('Geolocation not enabled by User');
        });
    } else {
        reject('Browser doesnt support Geolocation');
    }
});
