<script>
    import { onMount }       from 'svelte';
    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';
    import List   from './List.svelte';

    let authors  = $state(null);
    let note     = $state({source:null,rendered:null});
    let notes    = $state(null);
    const router = useTinyRouter();
    let {
        module = null,
        entity_id = null
    } = $props();

    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();
            delete notes[nid];
        } else {
            error(resp);
        }
    }

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

    async function load(id){
        const url = api(`notes/${module}/${id}`);
        const resp = await fetch(url,{credentials:'include'});
        if (resp.ok){
            const data = await resp.json();
            notes      = Object.values(data.notes).sort((a, b) => a.id - b.id);
            authors    = data.authors;
        } else {
            error(resp);
        }
    }

    async function saveNote(){
        const url  = api(`notes/${module}/${entity_id}`);
        const resp = await fetch(url,{
            credentials : 'include',
            method      : 'POST',
            body        : note.source
        });
        if (resp.ok){
            let newNote       = await resp.json();
            authors[user.id]  = user;
            notes.push(newNote);
            yikes();
            note.source       = null;
            note.rendered     = null;
            return true;
        } else {
            error(resp);
            return false;
        }
    }

    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 true;
        }
    }

    $effect(() => load(entity_id));
</script>

<List {authors} {module} {notes} />
<div class="editor">
<Editor simple={true} bind:value={note} onSet={saveNote} />
<button onclick={saveNote}>{t('save_object',{object:t('note')})}</button>
</div>