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

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

    import Position          from './Position.svelte';
    import PositionSelector  from './PositionSelector.svelte';

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

    let editable = $derived(document.state == 1);
    let sums = $derived.by(calcSums);
    let position_select = $state(false);

    async function addPosition(selected){
        const url  = api(`document/${document.id}/position`);
        const resp = await post(url,selected);
        if (resp.ok){
            document.positions = await resp.json();
            yikes();
        } else {
            error(resp);
        }
    }

    function calcSums(){
        let data  = {}
        let net   = 0;
        let gross = 0;
        for (let pos of Object.values(document.positions)){
            let net_price = pos.unit_price * pos.amount;
            let tax       = +pos.tax;
            data[tax]     = net_price + (data[tax] ? data[tax] : 0);
            net          += net_price;
        }
        for (let [tax, price] of Object.entries(data)) gross += price * (+tax+100)/100;
        data['net']   = net/100;
        data['gross'] = (gross/100).toFixed(2);
        return data;
    }

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

    async function movePos(number,step){
        const url  = 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(resp);
        }
    }

    async function drop(number){
        let confirmed = confirm(t('confirm_deletion').replace('{pos}',document.positions[number].item));
        if (!confirmed) return;
        const url  = 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(resp);
        }
    }
</script>

<legend>
    {t('positions')}
    {#if editable}
    <button onclick={() => position_select = true}>{t('add_object',{object:t('position')})}</button>
    {/if}
</legend>
{#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>{sums['net']}&nbsp;{document.currency}</td>
            <td colspan="2">{t('gross_sum')}</td>
            <td>{sums['gross']}&nbsp;{document.currency}</td>
            <td></td>
        </tr>
    </tbody>
</table>
{/if}
{#if position_select}
<PositionSelector close={() => position_select=false} doc={document} onSelect={addPosition} />
{/if}