<script lang="ts">
	import { type Food, FoodService } from '$lib/database/food'

	export let item: Food
	let amount: string = item.amount.toString()
	let per100: string = item.per100?.toString() ?? ''

	async function update(event: KeyboardEvent & { currentTarget: (EventTarget & HTMLTableCellElement) }) {
		if (event.key == 'Enter') {
			item.amount = parseInt(amount.trim())
			item.per100 = parseInt(per100.trim())
			const [newItem, err] = await FoodService.Update(item)
			amount = amount.trim()
			per100 = per100.trim()

			if (newItem && !err) {
				item = newItem
			}
		}
	}
</script>

<template>
	<tr class="border-b border-gray-200 dark:border-gray-700">
		<th class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap bg-gray-50 dark:text-white dark:bg-gray-800"
		    scope="row">
			{item.date}
		</th>
		<td class="px-6 py-4">
			{item.food}
		</td>
		<td class="px-6 py-4 bg-gray-50 dark:bg-gray-800">
			{item.description}
		</td>
		<td class="px-6 py-4"
		    contenteditable="true"
		    bind:innerText={amount}
		    on:keyup={update}>
		</td>
		<td class="px-6 py-4 bg-gray-50 dark:bg-gray-800"
		    contenteditable="true"
		    bind:innerText={per100}
		    on:keyup={update}>
		</td>
		<td class="px-6 py-4">
			{item.energy}
		</td>
	</tr>
</template>
