<script>
    import { onMount } from 'svelte';
    import { useTinyRouter } from 'svelte-tiny-router';
    import { t } from '../../translations.svelte';
    import { api, get, patch } from '../../urls.svelte';
    import { error, yikes } from '../../warn.svelte';

    let router = useTinyRouter();
    let messages = [];
    let timer = null;

    async function display(id){
        const url = api(`message/${id}`);
        const res = await get(url);
        if (res.ok){
            yikes();
            const json = await res.json();
            if (timer) clearTimeout(timer);
            for (let i in messages){
                if (messages[i].id == id){
                    messages[i].body = json.body;
                    timer = setTimeout(() => {mark_read(id)}, 2000);
                } else {
                    delete messages[i].body;
                }
            }
        } else {
            error(res);
        }
    }

    async function load(){
        const url = api('message');
        const res = await get(url);
        if (res.ok){
            messages = await res.json();
            yikes();
        } else {
            error(res);
        }
    }

    async function mark_read(id){
        timer = null;
        const url = api(`message/read/${id}`);
        const res = await patch(url);
        if (res.ok) {
            for (let i in messages){
                if (messages[i].id == id) messages[i].read = true;
            }
            yikes();
        } else {
            error(res);
        }
    }

    function showSettings(){
        router.navigate("message/settings");
    }

    onMount(load);
</script>

<fieldset>
    <legend>{@html t('messages')} <button onclick={showSettings}>{t('settings')}</button></legend>
    <table>
        <thead>
            <tr>
                <th>{t('timestamp')}</th>
                <th>{t('initiator')}</th>
                <th>{t('subject')}</th>
            </tr>
        </thead>
        <tbody>
            {#each messages as message}
            <tr class="message-{message.id}" onclick={ev => display(message.id)}>
                <td>
                    {#if message.read}→ {/if}
                    {message.timestamp}
                </td>
                <td>{message.sender}</td>
                <td>{message.subject}</td>
            </tr>
            {#if message.body}
            <tr class="message-{message.id} body">
                <td></td>
                <td colspan="2">
                    <pre>{message.body.trim()}</pre>
                </td>
            </tr>
            {/if}
            {/each}
        </tbody>
    </table>
</fieldset>