<script context="module">
    import {
        apiEndpoints,
        site,
        continents,
        countries,
        locations
    } from '../store'

    export async function preload (page, session) {
        const request = await this.fetch(apiEndpoints.gql, {
            method: 'post',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ query: `{
                site {
                    data {
                        description
                        explore_globe
                        explore_list
                        instagram
                        seo_name
                        seo_title_default
                        seo_description_default
                        seo_share_image { full_url }
                        credits_text
                        credits_list
                    }
                }
                continents {
                    data {
                        id
                        name
                    }
                }
                countries {
                    data {
                        id
                        name
                        slug
                        flag { full_url title }
                        continent { id }
                    }
                }
                locations (filter: { status_eq: "published" }) {
                    data {
                        id
                        name
                        slug
                        region
                        country { id }
                        description
                        coordinates
                    }
                }
            }`})
        })
        const result = await request.json()

        // Set data into store
        site.set(result.data.site.data[0])
        continents.set(result.data.continents.data)
        countries.set(result.data.countries.data)
        locations.set(result.data.locations.data)
    }
</script>

<script>
    // Manipulate countries data
    // Replace each countrie's continent by the database
    $countries.forEach(count => count.continent = $continents.find(cont => cont.id === count.continent.id))

    // Manipulate continents data
    // Push each country to its continent
    $countries.forEach(country => {
        const continent = $continents.find(cont => cont.id === country.continent.id)
        continent.countries = []
        !continent.countries.includes(country) && continent.countries.push(country)
    })

    // Manipulate locations data
    // Replace each location's country by the database
    $locations.forEach(loc => loc.country = $countries.find(cont => cont.id === loc.country.id))
</script>

<!-- <style src="../style/style.scss" global></style> -->
<style lang="scss" global>
    @import "./style/style.scss";
</style>

<slot></slot>
