<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 = $state([]);
	let users        = {};

	let sums         = {};

	function calcSums(){
		sums[0]      = 0;
		for (let user of Object.values(users)) sums[user.id] = 0;
		for (let transaction of transactions) {
			for (let user of Object.values(users)){
				if (user.id == transaction.destination.id) sums[user.id] += transaction.amount;
				if (user.id == transaction.source.id) sums[user.id] -= transaction.amount;
			}
			if (!transaction.destination.id) sums[0] += transaction.amount;
			if (!transaction.source.id)      sums[0] -= transaction.amount;
		}
	}

	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;
			calcSums();
		} else error(res);
	}

	function onSave(){
		load();
	}

	onMount(load);
</script>

<style>
	.amount{ text-align: right }
</style>

{#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 class="amount">
				{#if id == transaction.source.id}
				{(-transaction.amount).toFixed(2)}&nbsp;{account.currency}
				{/if}
				{#if id == transaction.destination.id}
				{(+transaction.amount).toFixed(2)}&nbsp;{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}
			<tr>
				<td>
					<br/>
					{t('sums')}
				</td>
				{#each Object.entries(users) as [id,user]}
				<th class="amount">
					{user.name}<br/>
					{sums[id].toFixed(2)}&nbsp;{account.currency}
				</th>
				{/each}
				<td class="amount">
					<br/>
					{sums[0].toFixed(2)}&nbsp;{account.currency}
				</td>
			</tr>
		</tbody>
	</table>
</fieldset>

<EntryForm {account} {onSave} />
{/if}