<script>
    import { Fa } from 'svelte-fa';
    import { GlobalSearch, ImageGrid, SearchAppRailAnchor} from '$lib/components';
    import { faGear } from '@fortawesome/free-solid-svg-icons';
    import { invoke } from '@tauri-apps/api/tauri'
    import { lastSearch, blacklist } from '$lib/settings';
    import { postSearchResults, loading, showSearch} from '$lib/stores';
    import {
        AppBar,
        AppRail,
        AppRailAnchor,
        AppShell,
        getDrawerStore, getToastStore
    } from '@skeletonlabs/skeleton';
    import PostList from '$lib/PostList';

    const drawerStore = getDrawerStore();
    const toastStore = getToastStore();

    function onSearch() {
        $loading = true;
        invoke('get_posts', { query: $lastSearch }).then((resPosts) => {
            postSearchResults.set(new PostList(resPosts).filterPosts($blacklist).getPosts());
            requestAnimationFrame(() => $loading = false);
        });
    }

    if ($postSearchResults === null) {
        onSearch();
    }

    lastSearch.subscribe(() => {
        onSearch();
    })
</script>

<AppShell>
    <svelte:fragment slot="pageHeader">
        {#if $showSearch}
            <AppBar>
                <GlobalSearch />
            </AppBar>
        {/if}
    </svelte:fragment>

    <svelte:fragment slot="sidebarLeft">
        <div class="h-dvh">
            <AppRail>
                <svelte:fragment slot="lead">
                    <SearchAppRailAnchor />
                </svelte:fragment>
                <svelte:fragment slot="trail">
                    <AppRailAnchor on:click={() => drawerStore.open()}>
                        <div class="flex flex-col gap-2 place-content-center">
                            <Fa size={'2x'} icon={faGear} />
                            <p>Settings</p>
                        </div>
                    </AppRailAnchor>
                </svelte:fragment>
            </AppRail>
        </div>
    </svelte:fragment>

    <svelte:fragment>
        <div class="overflow-scroll p-2">
            {#if $postSearchResults}
                <ImageGrid posts={$postSearchResults} />
            {/if}
        </div>
    </svelte:fragment>
</AppShell>