<script lang="ts">
	import { onMount } from 'svelte';
	import { startWebtransportStream } from './stream';
	import StreamUi from './StreamUi.svelte';

	interface Props {
		url: string;
		certHash: Array<number>;
		width: number;
		height: number;
		streamToken: string;
	}

	let { url, certHash, width, height, streamToken }: Props = $props();
	let loading = $state(true);
	let fullscreen = $state(false);
	let gameplayView: HTMLDivElement;
	let gameplayCanvas: HTMLCanvasElement;

	async function startStream() {
		// Append stream token to URL for proxy authentication
		const authenticatedUrl = url + (url.includes('?') ? '&' : '?') + 'token=' + encodeURIComponent(streamToken);
		await startWebtransportStream(
			authenticatedUrl,
			certHash,
			width,
			height,
			gameplayCanvas,
			gameplayCanvas,
			gameplayCanvas
		);
	}

	async function requestFullscreen() {
		// Update fullscreen var if fullscreen was exited outside our control
		if (document.fullscreenElement == null) {
			fullscreen = false;
		}

		if (fullscreen) {
			await document.exitFullscreen();
			fullscreen = false;
		} else {
			await gameplayCanvas.requestFullscreen();
			fullscreen = true;
		}
	}

	onMount(async () => {
		await startStream();
	});
</script>

<div id="gameplay-view" class="gameplay-view" bind:this={gameplayView}>
	<canvas id="gamestream-canvas" class="gamestream-canvas" bind:this={gameplayCanvas} tabindex="0"
	></canvas>
	<StreamUi fullscreenFunc={requestFullscreen}></StreamUi>
</div>

<style>
	.gameplay-view {
		height: 100vh;
		aspect-ratio: 16 / 9;

		margin-left: auto;
		margin-right: auto;
		background-color: black;

		position: relative;

		display: flex;
		flex-direction: column;
	}

	.gamestream-canvas {
		height: 100%;
		aspect-ratio: 16 / 9;

		position: relative;
		margin: auto;

		/*z-index: 1;*/
	}
</style>
