<script lang="ts">
	import { onMount } from "svelte";
	import getComponentForShare from "./contentType";
	const slug = window.location.pathname.split("/").pop();

	let component = null;

	onMount(async () => {
		const regex = /filename="(.*)"/gm;
		const res = await fetch(`/s/${slug}`);

		const contentType: string = res.headers.get("Content-Type");

		let filename: string;
		let m;
		while ((m = regex.exec(res.headers.get("Content-Disposition"))) !== null) {
			// This is necessary to avoid infinite loops with zero-width matches
			if (m.index === regex.lastIndex) {
				regex.lastIndex++;
			}
			filename = m[1];
		}

		document.title = filename;

		component = getComponentForShare(contentType,filename);
	});
</script>

<main>
	<div>{slug}</div>
	<div>
		{#if component === null}
			Loading data...
		{:else}
			{#await component}
				Loading data...
			{:then v } 
				<svelte:component this={v.default} />
			{/await}
		{/if}
	</div>
</main>

<style>
</style>
