<script>
    import { onDestroy, onMount } from 'svelte';
    import { api, eventStream, post }    from '../../urls.svelte';
    import { error, yikes } from '../../warn.svelte';
    import { t }            from '../../translations.svelte';

    let { items, selected = $bindable(null), location = null, drag_start = item => console.log({dragging:item}) } = $props();
    let eventSource      = null;
    let newItem = $state({name:null, code: null});

    function handleCreateEvent(evt){
        let json = JSON.parse(evt.data);
        if (json.item.location.id == location.id){
            items = [...items,json.item];
            selected = json.item;
        }
    }

    function handleEvent(evt,method){
        console.log(evt,method);
    }

	function handleDeleteEvent(evt){
        handleEvent(evt,'delete');
    }

    function handleUpdateEvent(evt){
        handleEvent(evt,'update');
    }

    function load(){
        try {
			eventSource = eventStream(handleCreateEvent,handleUpdateEvent,handleDeleteEvent);
        } catch (ignored) {}
    }

    async function saveNewItem(){
        newItem.location = location;
        const url = api('stock/item');
        const res = await post(url,newItem);
        if (res.ok) {
            yikes();
            const it = await res.json();
            console.log(it);
            items = [...items, it];
        } else error(res);
    }

    onDestroy(() => {
		if (eventSource) eventSource.close();
	});
    onMount(load);

</script>
<table>
    <thead>
        <tr>
            <th>{t('id')}</th>
            <th>{t('code')}</th>
            <th>{t('name')}</th>
        </tr>
    </thead>
    <tbody>
    {#each items as item}
    <tr onclick={ev => selected = item} ondragstart={e => drag_start(item)} draggable="true">
        <td title={`db id: ${item.id}`}>{item.owner_number}</td>
        <td>{item.code}</td>
        <td>{item.name}</td>
    </tr>
    {/each}
    {#if location}
    <tr>
        <td>{t('create_new_object',{object:t('item')})}</td>
        <td>
            <input type="text" bind:value={newItem.code} />
        </td>
        <td>
            <input type="text" bind:value={newItem.name}  />
            <button onclick={saveNewItem}>{t('save')}</button>
        </td>
    </tr>
    {/if}
    </tbody>
</table>
