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

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

	/** @type {import('./$types').PageData} */
	export let data;

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

	onMount(async () => {
		const response = await fetch('/api/list/' + $page.params.vorgang);
		const stream = 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);
		}
	});
</script>

<div class="-z-10 bg-white">
	<div class="flex flex-col items-center justify-center w-full">
		<h1 class="text-xl">Vorgang {$page.params.vorgang}</h1>
	</div>
	<div class="mx-auto flex justify-center max-w-7xl h-full">
		<ul class="divide-y divide-gray-100">
			{#each list as item}
				<li>
					<a
						href="/view/{$page.params.vorgang}/{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="M21 7.5l-2.25-1.313M21 7.5v2.25m0-2.25l-2.25 1.313M3 7.5l2.25-1.313M3 7.5l2.25 1.313M3 7.5v2.25m9 3l2.25-1.313M12 12.75l-2.25-1.313M12 12.75V15m0 6.75l2.25-1.313M12 21.75V19.5m0 2.25l-2.25-1.313m0-16.875L12 2.25l2.25 1.313M21 14.25v2.25l-2.25 1.313m-13.5 0L3 16.5v-2.25"
								/>
							</svg>
							<div class="min-w-0 flex-auto">
								<p class="text-sm font-semibold leading-6 text-gray-900">{item.name}</p>
								<p class="mt-1 truncate text-xs leading-5 text-gray-500">
									{shortenFileSize(item.size)}
								</p>
							</div>
						</div>
						<div class="hidden sm:flex sm:flex-col sm:items-end">
							<p class="text-sm leading-6 text-gray-900">3D Tatort</p>
							<p class="mt-1 text-xs leading-5 text-gray-500">
								Zuletzt geändert <time datetime="2023-01-23T13:23Z"
									>{timeElapsed(new Date(item.lastModified))}</time
								>
							</p>
						</div>
					</a>
				</li>
			{/each}
		</ul>
	</div>
</div>
