<script>
	import LineEditor from '../../Components/LineEditor.svelte';
	import { api, patch } from '../../urls.svelte';
	import { error, yikes } from '../../warn.svelte';
	let { account, transaction, users } = $props();

	async function setAmount(amount){
		return await update({amount});
	}
	async function setDate(date){
		return await update({date});
	}

	async function setDestination(destination){
		return await update({destination});
	}

	async function setPurpose(purpose){
		return await update({purpose});
	}

	async function setSource(source){
		return await update({source});
	}

	async function update(changes){
		let url = api('accounting/transaction/'+transaction.id);
		let res = await patch(url,changes);
		if (res.ok){
			yikes();
			return true;
		}
		error(res);
		return false;
	}
</script>

<tr>
	<td>
		<LineEditor type="date" wrapper="span" editable="true" value={transaction.date} onSet={setDate} />
	</td>
	{#each Object.entries(users) as [id,user]}
	<td class="amount">
		{#if id == transaction.source.id}
		-<LineEditor type="number" wrapper="span" editable="true" value={(+transaction.amount).toFixed(2)} onSet={setAmount} />&nbsp;{account.currency}
		{/if}
		{#if id == transaction.destination.id}
		<LineEditor type="number" wrapper="span" editable="true" value={(+transaction.amount).toFixed(2)} onSet={setAmount} />&nbsp;{account.currency}
		{/if}
	</td>
	{/each}
	<td class="party">
		{#if !transaction.source.id}
		← <LineEditor wrapper="span" editable="true" value={transaction.source.value} onSet={setSource} />
		{/if}
		{#if !transaction.destination.id}
		→ <LineEditor wrapper="span" editable="true" value={transaction.destination.value} onSet={setDestination} />
		{/if}
	</td>
	<td class="purpose">
		<LineEditor wrapper="span" editable="true" value={transaction.purpose} onSet={setPurpose} />
	</td>
	<td class="tags">
		{transaction.tags.join(', ')}
	</td>
</tr>
