<script>
	import { dev } from '$app/environment';
	import { onMount } from 'svelte';
	import { createPriority } from '$lib/priority.js';

	let base;

	if (dev) {
		console.log('Dev mode');
		base = 'http://10.39.253.16:8080';
	} else {
		console.log('Not dev mode');
		base = '';
	}

	const events = ['priority'];

	window.document.body.oncontextmenu = function () {
		return false;
	};

	let priority = createPriority();

	$: priority;

	LoadPriority();

	onMount(async () => {
		if (!dev) {
			const sse = StartSSE();
			return sse;
		}
	});

	function StartSSE() {
		let url = base + '/api/sse?';
		for (let e in events) {
			url += `event=${events[e]}&`;
		}
		console.log(`sse url: ${url}`);
		const sse = new EventSource(url);
		console.log(`subscribe: ${sse}`);

		sse.onopen = () => {
			console.log(`sse open ${Date.now()}`);
		};

		sse.addEventListener('priority', (e) => {
			let Msg = JSON.parse(e.data);
			console.log(JSON.stringify(Msg));
			console.log(`surfers: ${Msg.data.priority}`);
			priority.surfers = Msg.data.surfers;
			priority.round = Msg.data.round;
			priority.surfersCount = Msg.data.surfersCount;
		});

		return () => {
			sse.close();
			console.log(`sse closing ${Date.now()}`);
		};
	}

	async function LoadPriority() {
		const res = await fetch(`${base}/api/priority`);
		const data = await res.json();
		console.log(`load priority: ${JSON.stringify(data)}`);
		priority.surfers = data.surfers;
		priority.round = data.round;
		priority.surfersCount = data.surfersCount;
	}
</script>

<div class="wall">
	{#each Array(priority.surfersCount) as _, id}
		<div class="column">
			{#if priority.surfers[id].priority == 'P'}
				<div class="priority" id="p">{priority.surfers[id].priority}</div>
			{:else}
				<div class="priority" id="n">{priority.surfers[id].priority}</div>
			{/if}
			<div class="color" style="background-color: {priority.surfers[id].color}"></div>
		</div>
	{/each}
</div>

<style>
	:global(body) {
		overflow-y: hidden;
	}

	.wall {
		display: flex;
		margin: 0;
		padding: 0;
	}

	.column {
		display: flex;
		flex-direction: column;
		flex-grow: 1;
		height: 97vh;
		margin-right: 0.1vw;
		margin-left: 0.1vw;
		overflow: hidden;
		flex-basis: 0;
		/* border: 2px solid black; */
	}

	.column:first-child {
		margin-left: 0;
	}

	.column:last-child {
		margin-right: 0;
	}

	.priority {
		text-align: center;
		align-self: center;
		line-height: 24vh;
		overflow: hidden;
		/* border-bottom: 2px solid black; */
	}

	.priority#p {
		font-size: 18vmin;
		background-color: lightgray;
		width: 100%;
		margin-bottom: 0.1vh;
	}

	.priority#n {
		font-size: 14vmin;
		background-color: gray;
		width: 100%;
		margin-bottom: 0.1vh;
	}

	.color {
		flex-grow: 1;
	}
</style>
