<script>
    import Position from './Position.svelte';
    import { useTinyRouter } from 'svelte-tiny-router';
    import { onMount } from 'svelte';
    import { t } from '../../translations.svelte.js';

    var { document = $bindable(null), submit = (key,newVal) => {}, error = $bindable(null) } = $props();

    let editable = $derived(document.state == 1);

    async function updatePositions(resp){
        let json = await resp.json();
        document.positions = {};
        setTimeout(() => document.positions = json,100)
        error = null;
    }

    async function movePos(number,step){
        const url = `${location.protocol}//${location.host.replace('5173','8080')}/api/document/${document.id}/position`;
        const resp = await fetch(url,{
            method: 'PATCH',
            credentials:'include',
            body:JSON.stringify({position:number,move:step})
        });
        if (resp.ok){
            updatePositions(resp);
        } else {
            error = await resp.text();
        }
    }

    async function drop(number){
        let confirmed = confirm(t('confirm_deletion').replace('{pos}',document.positions[number].item));
        if (!confirmed) return;
        const url = `${location.protocol}//${location.host.replace('5173','8080')}/api/document/${document.id}/position`;
        const resp = await fetch(url,{
            method: 'DELETE',
            credentials:'include',
            body:JSON.stringify({position:number})
        });
        if (resp.ok){
            updatePositions(resp);
        } else {
            error = await resp.text();
        }
    }
</script>

{#if document.positions}
<table class="positions">
    <thead>
        <tr>
            <th>{t('pos')}</th>
            <th>{t('code')}</th>
            <th>{t('title_or_desc')}</th>
            <th>{t('amount')}</th>
            <th>{t('unit')}</th>
            <th>{t('unit_price')}</th>
            <th>{t('net_price')}</th>
            <th>{t('tax_rate')}</th>
        </tr>
    </thead>
    <tbody>
        {#each Object.entries(document.positions) as [id,pos]}
        <Position currency={document.currency} bind:pos={document.positions[id]} editable={editable} {submit} {movePos} {drop} />
        {/each}
        <tr class="sums">
            <td colspan="2"></td>
            <td>{t('net_sum')}</td>
            <td>{document.net_sum/100}&nbsp;{document.currency}</td>
            <td colspan="2">{t('gross_sum')}</td>
            <td>{document.gross_sum/100}&nbsp;{document.currency}</td>
            <td></td>
        </tr>
    </tbody>
</table>
{/if}
