<script lang="ts">
    import '../style/style.scss'
    import { page } from '$app/stores'
    import { setContext } from 'svelte'
    import '$utils/polyfills'
    // Components
    import Switcher from '$components/molecules/Switcher.svelte'
    import Footer from '$components/organisms/Footer.svelte'

    export let data: any
    export let count: any

    // Set global data
    setContext('global', {
        ...data,
        count,
    })
</script>

<Switcher />

<slot />

{#if !$page.params.photo}
    <Footer />
{/if}

<script context="module" lang="ts">
    import { fetchAPI } from '$utils/api'

    export async function load ({ page, fetch, session, stuff }) {
        const res = await fetchAPI(`
            query {
                locations: location (filter: { status: { _eq: "published" }}) {
                    id
                    name
                    slug
                    coordinates
                    country {
                        name
                        slug
                        flag { id }
                        continent { slug }
                    }
                    date_updated
                    photos (sort: "-date_created", limit: ${import.meta.env.VITE_PREVIEW_COUNT}) {
                        image {
                            id
                            title
                        }
                        date_created
                    }
                    has_poster
                }

                countries: country (filter: { status: { _eq: "published" }}) {
                    id
                    name
                    slug
                    flag { id }
                    locations { id slug }
                }

                continents: continent {
                    name
                    slug
                    rotation
                    countries { id slug }
                }

                settings {
                    seo_name
                    seo_title
                    seo_description
                    description
                    explore_list
                    limit_new
                    instagram
                    footer_links
                    newsletter_subtitle
                    newsletter_url
                    newsletter_text
                }

                shop {
                    enabled
                    module_title
                    module_text
                    module_image {
                        id
                        title
                    }
                }

                # Count
                countPhotos: photo_aggregated {
                    count { id }
                }
                countTotalPhotosByLocation: photo_aggregated (groupBy: "location") {
                    group
                    count { id }
                }
                countLocations: location_aggregated {
                    count { id }
                }
                countCountries: country_aggregated {
                    count { id }
                }
            }
        `)

        const { data } = res

        // Filter continents with linked countries
        const filteredContinents = data.continents.filter((cont: any) => cont.countries.length)

        /**
         * For each photos count, find the country and add the sum to it
         */
        // Add count key
        data.countries.forEach((country: any) => country.count = 0)

        // Loop through totals by location
        data.countTotalPhotosByLocation.forEach(({ group, count }: { group: { location: number }, count: { id: number }}) => {
            const locationId = group.location
            const photosCount = Number(count.id)
            const countryIndex = data.countries.findIndex((country: any) => {
                // Find the location of a country
                return country.locations.find((location: any) => {
                    // Match the count location ID to the country location ID
                    return Number(location.id) === locationId
                })
            })

            // Increment the count value found above
            data.countries[countryIndex].count += photosCount
        })

        return {
            props: {
                data: {
                    ...data,
                    continents: filteredContinents,
                },
                count: {
                    photos: data.countPhotos[0].count.id,
                    locations: data.countLocations[0].count.id,
                    countries: data.countCountries[0].count.id,
                },
            },
            stuff: data,
        }
    }
</script>