<style>
	ul {
		min-width: 24rem;
	}
</style>

<script>
	import { onMount } from 'svelte';
	import { page } from '$app/stores';

	/**
	 * @type any[]
	 */
	let list = [];
	//$: list;

	onMount(async () => {
		const response = await fetch('/api/list');
		const stream = await response.body;
		if (!stream) return;

		const reader = stream.getReader();

		while (true) {
			const { done, value } = await reader.read();
			if (done) return;

			const objs = new TextDecoder()
				.decode(value)
				.split('\n')
				.filter((i) => i.length > 0)
				.map((i) => JSON.parse(i));

			console.log(objs);
			list = list.concat(objs);
		}
	});

	async function delete_item(ev) {
		let delete_item = window.confirm("Bist du sicher?");

		if (delete_item) {
				let filename = event.currentTarget.id.split('del__')[1]

				// delete request
				// --------------

				let url = `/api/list/${filename}`

				console.log(`--- ${filename} + ${url}`)
				try {
					const response = await fetch(url,
						{method: 'DELETE'}
					)
					if (response.status == 204) {
						setTimeout(() => {window.location.reload()}, 500)
					}
				} catch (error) {
					console.log(error.message)
				}

			}

	}
</script>

<div class="-z-10 bg-white">
	<div class="flex flex-col items-center justify-center w-full">
		<h1 class="text-xl">Liste der Vorgänge</h1>
	</div>
	<div class="mx-auto flex justify-center max-w-7xl h-full">
		<ul role="list" class="divide-y divide-gray-100">
			{#each list as item}
				<li>
					<a href="/list/{item.name}" class="flex justify-between gap-x-6 py-5">
						<div class="flex gap-x-4">
							<svg
								xmlns="http://www.w3.org/2000/svg"
								fill="none"
								viewBox="0 0 24 24"
								stroke-width="1.5"
								stroke="currentColor"
								class="w-6 h-6"
							>
								<path
									stroke-linecap="round"
									stroke-linejoin="round"
									d="M2.25 12.75V12A2.25 2.25 0 014.5 9.75h15A2.25 2.25 0 0121.75 12v.75m-8.69-6.44l-2.12-2.12a1.5 1.5 0 00-1.061-.44H4.5A2.25 2.25 0 002.25 6v12a2.25 2.25 0 002.25 2.25h15A2.25 2.25 0 0021.75 18V9a2.25 2.25 0 00-2.25-2.25h-5.379a1.5 1.5 0 01-1.06-.44z"
								/>
							</svg>
							<div class="min-w-0 flex-auto">
								<span class="text-sm font-semibold leading-6 text-gray-900">{item.name}</span>
								<!-- Delete button -->
								<button
								style="padding: 2px"
								id="del__{item.name}"
								on:click|preventDefault={delete_item}
								>
									<svg
									height="20" width="20" xmlns="http://www.w3.org/2000/svg"><path d="m8 3v1 1h1v-1h4v1h1v-1-1zm-4 3v1h14v-1zm2 2v11h1 9v-1-10h-1v10h-8v-10z" fill="#373737" transform="translate(1 1)"/></svg>
								</button>
							</div>
						</div>
						<div class="hidden sm:flex sm:flex-col sm:items-end">
							<p class="text-sm leading-6 text-gray-900">Vorgang</p>
						</div>
					</a>
				</li>
			{/each}
		</ul>
	</div>
</div>
