<script>
    import { useTinyRouter } from 'svelte-tiny-router';

    import { api }           from '../../urls.svelte.js';
    import { error, yikes }  from '../../warn.svelte';
    import { t }             from '../../translations.svelte.js';
    import { user }          from '../../user.svelte.js';

    import Editor from '../../Components/MarkdownEditor.svelte';

    let { authors, module, notes = $bindable() }  = $props();
    const router = useTinyRouter();

    async function drop(nid){
        if (!confirm(t('confirm_delete',{element:t('note')}))) return;
        const url  = api(`notes/${nid}`);
        const resp = await fetch(url,{
            credentials : 'include',
            method      : 'DELETE'
        });
        if (resp.ok) {
            yikes();
            notes = notes.filter((itm,idx) => itm.id != nid);
        } else {
            error(resp);
        }
    }

    function goToEntity(note){
        router.navigate(`/${note.module}/${note.entity_id}/view`);
    }

    function title(note){
        let title = t(note.module);
        if (note.module == 'wiki') title += ':';
        title += ' ';
        title += note.entity_id;
        return title;
    }

    async function update(nid,src){
        const url  = api(`notes/${nid}`);
        const resp = await fetch(url,{
            credentials : 'include',
            method      : 'PATCH',
            body        : src
        });
        if (resp.ok) {
            yikes();
            return true;
        } else {
            error(resp);
            return false;
        }
    }
</script>

{#if notes}
{#each notes as note (note.id)}
<fieldset>
    {#if module}
    <legend class="author">{authors[note.user_id].name}</legend>
    {:else}
    <legend class="entity" onclick={() => goToEntity(note)}>{title(note)}</legend>
    {/if}
    <legend class="time">
        {#if !module} {authors[note.user_id].name} – {/if}
        {note.timestamp.replace('T',' ')}
        {#if user.id == note.user_id}
        <button class="symbol" onclick={() => drop(note.id)}></button>
        {/if}
    </legend>
    <Editor value={note.text} onSet={(newVal) => update(note.id,newVal)} editable={user.id == note.user_id} />
</fieldset>
{/each}
{/if}