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

	import EntryForm from './add_entry.svelte';

	let { id }       = $props();
	let account      = $state(null);
	let transactions = [];
	let users        = {};

	async function load(){
		let url = api(`accounting/${id}`);
		let res = await get(url);
		if (res.ok) {
			yikes();
			let json     = await res.json();
			transactions = json.transactions;
			users        = json.user_list;
			account      = json.account;
			console.log(users);
		} else error(res);
	}

	onMount(load);
</script>
{#if account}
<fieldset>
	<legend>{account.name}</legend>
	<table>
		<thead>
			<tr>
				<th>{t('date')}</th>
				{#each Object.entries(users) as [id,user]}
				<th>{user.name}</th>
				{/each}
				<th>{t('other party')}</th>
				<th>{t('purpose')}</th>
			</tr>
		</thead>
		<tbody>
			{#each transactions as transaction, i}
			<tr>
				<td>{transaction.date}</td>
				{#each Object.entries(users) as [id,user]}
				<td>
				{#if id == transaction.source.id}
				{-transaction.amount} {account.currency}
				{/if}
				{#if id == transaction.destination.id}
				{transaction.amount} {account.currency}
				{/if}
				</td>
				{/each}
				<td>
				{#if !transaction.source.id}
				{transaction.source.value}
				{/if}
				{#if !transaction.destination.id}
				{transaction.destination.value}
				{/if}
				</td>
				<td>{transaction.purpose}</td>
			</tr>
			{/each}
		</tbody>
	</table>
</fieldset>

<EntryForm {account} />
{/if}