<script>
    import { Header, ImageGrid } from '$lib/components';
    import { invoke } from '@tauri-apps/api/core'
    import PostList from '$lib/PostList';
    import useSettings from "$lib/useSettings.svelte.js";
    import {onMount} from "svelte";
    import {loading, postSearchResults} from "$lib/stores.js";

    const settings = useSettings();

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

    onMount(() => {
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.has('search')) {
            onSearch(urlParams.get('search'), false);
            return;
        }

        if ($postSearchResults === null) {
            onSearch(settings.lastSearch, true);
        }
    })
</script>

<div>
    <Header onsubmit={(val = '', explicitRefresh = false) => {onSearch(val, explicitRefresh);}}></Header>
    <main>
        <div class="overflow-scroll p-2">
            {#if $postSearchResults}
                <ImageGrid posts={$postSearchResults} />
            {/if}
        </div>
    </main>
</div>