<script>
    import { onMount }       from 'svelte';
    import { useTinyRouter } from 'svelte-tiny-router';
    import { api }           from '../../urls.svelte.js';
    import { t }             from '../../translations.svelte.js';

    import Bookmark from '../bookmark/Template.svelte';

    const router = useTinyRouter();
    console.log(router);
    let bookmarks = $state(null);
    let error = $state(null);
    let fulltext = false;
    let key = $state(router.getQueryParam('key'));
    let input = $state(router.getQueryParam('key'));
    let projects = $state(null);
    let tasks = $state(null);

    async function setKey(ev){
        if (ev) ev.preventDefault();
        key = input;

    }

    onMount(() => {
        let params = new URLSearchParams(location.search);
        key        = params.get('key');
    });

    function doSearch(ignored){
        let url = window.location.origin + window.location.pathname;
        if (key) url += '?key=' + encodeURI(key);
        window.history.replaceState(history.state, '', url);

        const data = { key : key, fulltext : fulltext };
        const options = {
            credentials:'include',
            method: 'POST',
            body: JSON.stringify(data)
        };
        fetch(api('bookmark/search'),options).then(handleBookmarks);
        fetch(api('project/search'),options).then(handleProjects);
        fetch(api('task/search'),options).then(handleTasks);
    }

    function go(path){
        router.navigate(path);
        return false;
    }

    async function handleBookmarks(resp){
        if (resp.ok){
            const res = await resp.json();
            bookmarks = Object.keys(res).length ? res : null;
        } else {
            error = await resp.text();
        }
    }

    async function handleProjects(resp){
        if (resp.ok){
            const res = await resp.json();
            projects = Object.keys(res).length ? res : null;
        } else {
            error = await resp.text();
        }
    }

    async function handleTasks(resp){
        if (resp.ok){
            const res = await resp.json();
            tasks = Object.keys(res).length ? res : null;
        } else {
            error = await resp.text();
        }
    }

    $effect(() => doSearch(key))

</script>

<fieldset class="search">
    <legend>{t('search')}</legend>
    {#if error}
    <span class="error">{error}</span>
    {/if}
    <form onsubmit={setKey}>
    <label>
        {t('key')}
        <input type="text" bind:value={input} />
    </label>
    <label>
        <input type="checkbox" bind:checked={fulltext} />
        {t('fulltext')}
    </label>
    <button type="submit">{t('go')}</button>
    </form>
</fieldset>
{#if projects}
<fieldset>
    <legend>
        {t('projects')}
    </legend>
    <ul>
        {#each Object.values(projects) as project}
        <li>
            <a href="#" onclick={e=>go(`/project/${project.id}/view`)} >{project.name}</a>
        </li>
        {/each}
    </ul>
</fieldset>
{/if}
{#if tasks}
<fieldset>
    <legend>
        {t('tasks')}
    </legend>
    <ul>
        {#each Object.values(tasks) as task}
        <li>
            <a href="#" onclick={e=>go(`/task/${task.id}/view`)} >{task.name}</a>
        </li>
        {/each}
    </ul>
</fieldset>
{/if}
{#if bookmarks}
<fieldset>
    <legend>
        {t('bookmarks')}
    </legend>
    <ul>
    {#each Object.values(bookmarks) as bookmark}
        <li>
            <a href={bookmark.url} target="_blank">{@html bookmark.comment.rendered}</a>
        </li>
    {/each}
    </ul>
</fieldset>
{/if}