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

	const router = useTinyRouter();

	let accounts = [];

	async function load(){
		let url = api('accounting');
		let res = await get(url);
		if (res.ok){
			yikes();
			accounts = await res.json();
		} else error(res);
	}

	function newAccount(){
		router.navigate('/accounting/new');
	}

    function onclick(e){
        e.preventDefault();
        let href = e.target.getAttribute('href');
        if (href) router.navigate(href);
        return false;
    }

	onMount(load);
</script>

<svelte:head>
	<title>Umbrella – {t('accounts')}</title>
</svelte:head>

<fieldset>

	<span></span>
	<span>
		<button onclick={newAccount}>{t('create_new_object',{'object':t('account')})}</button>
	</span>

	<ul>
	{#each accounts.toSorted((a,b) => a.name.localeCompare(b.name)) as account (account.id)}
		<li>
			<a {onclick} href="/account/{account.id}">{account.name}</a>
		</li>
	{/each}
	</ul>
	<legend>{t('accounts')}</legend>

</fieldset>