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


	//user's stuff
	let currentUser;
	let allUsers = [];
	let idInterval;
	onMount( async() => {
		currentUser = 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/game/ranking`)
		.then( x => x.json() );
		idInterval = setInterval(fetchScores, 10000);
	})

	onDestroy( async() => {
		clearInterval(idInterval);
	})

	function fetchScores() {
		fetch(`http://${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}/api/v2/game/ranking`)
		.then( x => x.json() )
		.then( x => allUsers = x );
	}
</script>
<Header />
<br />

<div class="principal-div">
	<table class="stats-table">
		<thead>
			<tr>
				<th>#</th>
				<th>Username</th>
				<th>Win</th>
				<th>Lose</th>
				<th>Draw</th>
				<th>Games Played</th>
			</tr>
		</thead>
		<tbody>
			{#each allUsers as user, i}
				<tr>
					<th>{i + 1}</th>
					{#if user.username === currentUser.username}
						<td><b>You ({user.username})</b></td>
					{:else}
					<td>{user.username}</td>
					{/if}
					<td>{user.stats.winGame}</td>
					<td>{user.stats.loseGame}</td>
					<td>{user.stats.drawGame}</td>
					<td>{user.stats.totalGame}</td>
				</tr>
			{/each}
		</tbody>
	</table>
</div>

<style>

		.principal-div {
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.stats-table {
		margin-left: auto;
		margin-right: auto;
		font-size: 0.9em;
		font-family: sans-serif;
		min-width: 400px;
	}

	.stats-table thead tr {
		background-color: #618174;
		color: #ffffff;
	}

	.stats-table th,
	.stats-table td {
		padding: 12px 15px;
	}

	.stats-table tbody tr {
		border-bottom: 1px solid #dddddd;
	}

	.stats-table tbody tr:nth-of-type(even) {
		background-color: #f3f3f3;
	}

	.stats-table tbody tr:last-of-type {
		border-bottom: 2px solid #618174;
	}

	.stats-table tbody tr.active-row {
		font-weight: bold;
		color: #618174;
	}
</style>
