
<script lang="ts">
	import { onMount, onDestroy } from "svelte";
	import Header from '../../pieces/Header.svelte';
	import MatchListElem from "../../pieces/MatchListElem.svelte";
	import { fade, fly } from 'svelte/transition';


	import * as pongSpectator from "./client/pongSpectator";
	import { gameState } from "./client/ws";

	//user's stuff
	let user;
	let allUsers;

	//Game's stuff client side only
	const gameAreaId = "game_area";
	let sound = "off";
	let matchList = [];

	//html boolean for pages
	let hiddenGame = true;

	let watchGameStateInterval;
	const watchGameStateIntervalRate = 142;

	onMount( async() => {
		user = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/user`)
		.then( x => x.json() );
		allUsers = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/user/all`)
		.then( x => x.json() );
		const responseForMatchList = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/game/match/all`)
		const jsonForMatchList = await responseForMatchList.json();
		matchList = jsonForMatchList;
	})

	onDestroy( async() => {
		clearInterval(watchGameStateInterval);
		pongSpectator.destroy();
	})

	async function initGameSpectator(gameSessionId: string, matchOptions: pongSpectator.MatchOptions)
	{
		watchGameStateInterval = setInterval(watchGameState, watchGameStateIntervalRate);
		pongSpectator.init(matchOptions, sound, gameAreaId, gameSessionId);
		hiddenGame = false;
	};

	const watchGameState = () => {
		console.log("watchGameState")
		if (gameState) { // trigger Svelte reactivity
			gameState.matchStarted = gameState.matchStarted;
			gameState.matchEnded = gameState.matchEnded;
			gameState.matchAborted = gameState.matchAborted;
		}
		if (gameState.matchAborted || gameState.matchEnded)
		{
			clearInterval(watchGameStateInterval);
			console.log("watchGameState, end")
			setTimeout(() => {
				resetPage();
				console.log("watchGameState : setTimeout")
			}, 5000);
		}
	}

	function leaveMatch() {
		clearInterval(watchGameStateInterval);
		resetPage();
	};

	async function resetPage() {
		hiddenGame = true;
		pongSpectator.destroy();
		fetchMatchList();
	};

	async function fetchMatchList() {
		matchList = await fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/game/match/all`)
		.then( x => x.json() );
	};


</script>
<!--  -->

<Header />
<!-- <div id="game_page"> Replacement for <body>.
	Might become useless after CSS rework. -->
<div id="game_page">

	{#if !hiddenGame}
		{#if gameState.matchEnded}
			<div class="div_game" in:fly="{{ y: 10, duration: 1000 }}">
				<p>The match is finished !</p>
			</div>
		{/if}
	{/if}

	<div id="canvas_container" hidden={hiddenGame}>
		<canvas id={gameAreaId}/>
	</div>

	{#if !hiddenGame}
		{#if !gameState.matchEnded}
			<div class="div_game">
				<button class="pong_button" on:click={leaveMatch}>leave</button>
			</div>
		{/if}
	{/if}

<!--  -->

	{#if hiddenGame}
		<div class="div_game" in:fly="{{ y: 10, duration: 1000 }}">
			<fieldset>
				<legend>options</legend>
				<button class="pong_button" on:click={fetchMatchList}>Reload</button>
				<div>
					<p>sound :</p>
					<input type="radio" id="sound_on" name="sound_selector" bind:group={sound} value="on">
					<label for="sound_on">on</label>
					<input type="radio" id="sound_off" name="sound_selector" bind:group={sound} value="off">
					<label for="sound_off">off</label>
				</div>
			</fieldset>
			{#if matchList.length !== 0}
				<menu id="match_list">
					{#each matchList as match}
						<MatchListElem match={match} on:click={(e) => initGameSpectator(match.gameServerIdOfTheMatch, match.gameOptions)} />
					{/each}
				</menu>
			{:else}
				<p>no match ongoing</p>
			{/if}
		</div>
	{/if}

</div> <!-- div "game_page" -->

<!--  -->
<style>
@font-face {
	font-family: "Bit5x3";
	src:
		url("/fonts/Bit5x3.woff2") format("woff2"),
		local("Bit5x3"),
		url("/fonts/Bit5x3.woff") format("woff");
	font-weight: normal;
	font-style: normal;
	font-display: swap;
}

#game_page {
	margin: 0;
	padding: 20px;
	background-color: #222425;
	position: relative;
	width: 100%;
	height: 100%;
}
#canvas_container {
	margin-top: 20px;
	text-align: center;
	/* border: dashed rgb(245, 245, 245) 5px; */
	/* max-height: 80vh; */
	/* overflow: hidden; */
}
canvas {
	/* background-color: #ff0000; */
	background-color: #333333;
	max-width: 75vw;
	/* max-height: 100vh; */
	width: 80%;
}

.div_game {
	text-align: center;
	font-family: "Bit5x3";
	color: rgb(245, 245, 245);
	font-size: x-large;
}
.div_game fieldset {
	max-width: 50vw;
	width: auto;
	margin: 0 auto;
}
.div_game fieldset div {
	padding: 10px;
}
.pong_button {
	font-family: "Bit5x3";
	color: rgb(245, 245, 245);
	background-color: #333333;
	font-size: x-large;
	padding: 10px;
}

#match_list {
	font-family: 'Courier New', Courier, monospace;
	font-size: large;
}

</style>
