<script lang="ts">
    import { onMount } from 'svelte';

    import { inboxApi } from '$lib/stores/apiStore'
    import type { InboxItem } from '$lib/dashclient'
    import InvertableIconButton from '$lib/components/InvertableIconButton.svelte';
    import InputText from '$lib/components/TextInput.svelte';
    
    let updateTimeout: NodeJS.Timeout;

    let inboxItem: InboxItem = {
        "item": ""
    };

    let inboxItems: InboxItem[] = [];

    async function fetchInboxItems() {
        inboxApi.getInboxItems().then(resp => (inboxItems = resp));
    }

    onMount(() => {
        fetchInboxItems();
    });
    
    function writeInboxItem() {
        // clearTimeout(updateTimeout);
        // console.log(inboxItem);
        
        // updateTimeout = setTimeout(function() {
        //     inboxApi.addInboxItem({"inboxItem":inboxItem}).then(() => {
        //         fetchInboxItems();
        //         inboxItem.item = "";
        //     });
        // }, 1000);

        inboxApi.addInboxItem({"inboxItem":inboxItem}).then(() => {
            fetchInboxItems();
            inboxItem.item = "";
        });
    }

    // function prepareInboxItemForWrite(inboxItem: InboxItem): InboxItem {
    //     return {
    //         item: inboxItem.item,
    //     };
    // }

    function deleteInboxItem(item: InboxItem) {
        inboxApi.deleteInboxItem({"item": item.id}).then(() => {
            inboxItems = inboxItems.filter(i => i.id !== item.id);
        });
    }

    function handleKeyPress(event: KeyboardEvent) {
        if (event.key === 'Enter') {
            writeInboxItem();
        }
    }
</script>

<div class="flex justify-center mt-8">
    <div class="w-11/12 flex-col items-center">
        <div>
            <InputText bind:val={inboxItem.item} placeholder="Add inbox item" onKeypress={handleKeyPress} doAutofocus={true}/>
        </div>

        {#each inboxItems as item (item.id)}
            <div class="flex items-center content-center space-y-1">
                <div class="h-4 w-4 mr-2">
                    <InvertableIconButton label="" icon="/trashcan.svg" clickHandler={() => deleteInboxItem(item)} />
                </div> 
                <!-- <button on:click={() => deleteInboxItem(item)} class="delete-button">Delete</button> -->
                {#if item.item.includes('http')}
                    <a href={item.item} class="underline hover:text-slate-600 dark:hover:text-slate-200">{item.item}</a>
                {:else}
                    <div class="max-w-xl">{item.item}</div>
                {/if}
            </div>
        {/each}
    </div>
</div>

<style>
</style>
