<script lang="ts">
    import '../style/style.scss'
    import { navigating, page } from '$app/stores'
    import { onMount, setContext } from 'svelte'
    import { pageLoading, previousPage } from '$utils/stores'
    import { scrollToTop } from '$utils/functions'
    import { DURATION } from '$utils/contants'
    import '$utils/polyfills'
    // Components
    import SVGSprite from '$components/SVGSprite.svelte'
    import PageTransition from '$components/PageTransition.svelte'
    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,
    })


    /**
     * On page change
     */
    // Store previous page (for photo Viewer close button)
    let previous = ''
    page.subscribe(value => {
        $previousPage = previous
        previous = value.path
    })

    // Define page loading from navigating store
    navigating.subscribe((store: any) => {
        if (store) {
            $pageLoading = true

            // Turn page loading when changing page
            setTimeout(() => {
                $pageLoading = false
            }, DURATION.PAGE_IN * 1.25)

            // Scroll back to top between page transitions
            setTimeout(() => {
                // Disable scroll when changing filters on /photos and shop?
                if (!$page.query.get('country') && !$page.path.includes('/shop/poster')) {
                    scrollToTop()
                }
            }, DURATION.PAGE_OUT + 1)
        }
    })

    onMount(() => {
        // Avoid FOUC
        document.body.style.opacity = '1'
    })
</script>

<Switcher isOver={!!$page.params.location && !!$page.params.photo} />

<PageTransition path={$page.path}>
    <slot />
</PageTransition>

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

{#if $pageLoading}
    <div class="page-loading" />
{/if}

<SVGSprite />

<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 (
                    filter: { status: { _eq: "published" }},
                ) {
                    count { id }
                }
                countTotalPhotosByLocation: photo_aggregated (
                    groupBy: "location",
                    filter: { status: { _eq: "published" }},
                ) {
                    group
                    count { id }
                }
                countLocations: location_aggregated (
                    filter: { status: { _eq: "published" }},
                ) {
                    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>