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

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

	let defaultAccount = {
		id       : 0,
		name     : '',
		currency : ''
	};
	let { account = defaultAccount, new_account = false } = $props();

	let entry = $state({
		account,
		date : new Date().toISOString().substring(0, 10),
		source : {
			display: user.name,
			id: user.id
		},
		destination : {},
		amount : 0.0,
		purpose : {}
	});
	let router = useTinyRouter();

	async function getTerminal(text,url){
		var res = await post(url,text);
        if (res.ok){
            yikes();
            const input = await res.json();
            return Object.values(input).map(user => { return {...user, display: user.name}});
        } else {
            error(res);
            return {};
        }
	}

	async function getDestinations(text){
		var url = api('accounting/destinations');
		return await getTerminal(text,url);
	}

	async function getSources(text){
		var url = api('accounting/sources');
		return await getTerminal(text,url);
	}

	async function save(){
		let data = {
			...entry,
			purpose: entry.purpose.display
		}
		let url = api('accounting');
		let res = await post(url, data);
		if (res.ok) {
			yikes();
			router.navigate('/accounting');
		} else error(res);
	}
</script>

<style>
	hr{
		grid-column: 1 / -1;
		margin: 0.5rem 0;
        border: 0;
        height: 1px;
        align-self: center;
        background: red;
	}
</style>

<fieldset class="grid2">
	{#if new_account}
		<legend>{t('create_new_object',{object:t('account')})}</legend>
		<span style="display:none"></span>
		<span>{t('account name')}</span>
		<span>
			<input type="text" bind:value={entry.account.name} />
		</span>
		<span>{t('currency')}</span>
		<span>
			<input type="text" bind:value={entry.account.currency} />
		</span>
		<hr/>
		<span style="grid-column-end: span 2">{t('first transaction')}</span>
	{:else}
		<legend>{t('add_object',{object:t('transaction')})}</legend>
		<span style="display:none"></span>
	{/if}

	<span>{t('date')}</span>
	<span>
		<input type="date" value={entry.date} />
	</span>

	<span>{t('source')}</span>
	<Autocomplete bind:candidate={entry.source} getCandidates={getSources} />

	<span>{t('destination')}</span>
	<Autocomplete bind:candidate={entry.destination} getCandidates={getDestinations} />

	<span>{t('amount')}</span>
	<span>
		<input type="number" bind:value={entry.amount} />&nbsp;{entry.account.currency}
	</span>

	<span>{t('purpose')}</span>
	<Autocomplete bind:candidate={entry.purpose} />

	<span></span>
	<span>
		<button onclick={save}>{t('save')}</button>
	</span>
</fieldset>
