<script>
    import { onMount } from 'svelte'
    import { locations } from 'utils/store'

    // Props
    export let type = ''
    let scope
    let globe

    // Functions
    const resize = () => {
        globe.resize()
        globe.update()
    }
    const update = () => {
        requestAnimationFrame(update)
        globe.update()
    }


    /*
    ** Run code when mounted
    */
    onMount(async () => {
        // For browser only
        if (process.browser) {
            // Import libraries and code
            let WebglGlobe
            await import('globe').then(module => WebglGlobe = module.default)

            // Init the globe from library
            globe = new WebglGlobe({
                el: scope,
                texture: '/img/globe/map-2k.png',
                markers: [...$locations.map(location => {
                    return {
                        name: location.name,
                        slug: location.slug,
                        countryName: location.country.name,
                        countrySlug: location.country.slug,
                        lat: location.coordinates.lat,
                        lng: location.coordinates.lng
                    }
                })],
                onLinkClicked: () => {},
                cameraDistance: 3
            })

            // Run the globe
            resize()
            update()
        }
    })
</script>

<svelte:window on:resize={resize} />

<div class="globe" bind:this={scope} />
