<script>
	heat;
	// import { page } from '$app/stores';
	import { onMount } from 'svelte';
	import { dev } from '$app/environment';
	import { priority } from '$lib/stores/priority.js';
	import Select from '$lib/select.svelte';
	import Button from '$lib/button.svelte';

	if (dev) {
		console.log('Dev mode');
	} else {
		console.log('Not dev mode');
	}

	const events = ['priority', 'time'];

	let saved = false;

	$: if (saved && $priority) {
		window.sessionStorage.setItem('priority', JSON.stringify($priority));
		console.log(`saved: ${JSON.stringify($priority)}`);
	}

	let width;
	let heat;
	$: heats = [];

	// $: surfers = [];
	$: min = 0;
	$: sec = 0;
	// $: end = false;
	// $: start = false;

	function resetHeat() {
		heat = {
			name: '',
			number: 0,
			round: '',
			category: '',
			timer: 0,
			surfers: []
		};
	}

	onMount(async () => {
		let ses = window.sessionStorage.getItem('priority');
		if (ses) {
			$priority = JSON.parse(ses);
			console.log(`loaded: ${JSON.stringify($priority)}`);
		}
		saved = true;
		loadHeats();
		const unsub = Subscribe();
		return unsub;
	});

	function pad2(number) {
		return `00${number}`.slice(-2);
	}

	async function loadHeats() {
		// resetHeat();
		const res = await fetch(`/api/loadheats`);
		const data = await res.json();
		for (let i in data) {
			heats[i] = data[i];
			heats[i].name = `${data[i].round} ${data[i].number} ${data[i].category}`;
			heats = heats;
			console.log(`${i} retval: ${JSON.stringify(data[i])}`);
		}
	}

	function Subscribe() {
		let url = '/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.onmessage = (e) => {
			let Msg = JSON.parse(e.data);
			console.log(`received: ${JSON.stringify(Msg)}`);
			if (Msg.mode === 'priority') {
				console.log(`priority: ${Msg.priority}`);
				for (let i in $priority.surfers) {
					$priority.surfers[i].priority = Msg.priority[i];
				}
			} else if (Msg.mode === 'time') {
				// console.log(`duration: ${Msg.duration}`);
				let min_sec = Msg.duration.split(':');
				min = min_sec[0];
				sec = min_sec[1];
				// console.log(`min & sec = ${min} & ${sec}`);
				if (!$priority.start) {
					$priority.start = true;
				}
			} else if (Msg.mode === 'stop') {
				console.log(`stop duration: ${Msg.duration}`);
				end = true;
				$priority.start = false;
			}
		};
		return () => {
			sse.close();
			console.log(`sse closing ${Date.now()}`);
		};
	}

	async function dblclick(id) {
		console.log(`dblclick = ${$priority.surfers[id]}`);
		if ($priority.surfers[id] === 'P') {
			console.log('pressed P');
		} else {
			console.log(`pressed: [${id}] ${$priority.surfers[id].priority}`);
		}
		const res = await fetch(`/api/stopheat`);
		const data = await res.json();
		console.log(`stop: ${JSON.stringify(data)}`);
		console.log(`dblclick = ${JSON.stringify(pri)}`);
	}

	async function startHeat() {
		const res = await fetch(`/api/startheat`, {
			method: 'POST',
			body: JSON.stringify({
				data: JSON.stringify(heat),
				cmd: 'start',
				event: 'timer'
			}),
			headers: {
				'Content-Type': 'application/json'
			}
		});
		console.log(`retval: ${JSON.stringify(res)}`);
		$priority.start = true;
		$priority.end = false;
	}

	async function stopHeat() {
		const res = await fetch(`/api/stopheat`, {
			method: 'POST',
			body: JSON.stringify({
				data: JSON.stringify(heat),
				cmd: 'stop',
				event: 'timer'
			}),
			headers: {
				'Content-Type': 'application/json'
			}
		});
		console.log(`retval: ${JSON.stringify(res)}`);
		$priority.reset;
		$priority.start = false;
		$priority.end = true;
		resetHeat();
		console.log(`stopHeat: ${JSON.stringify($priority)}`);
	}

	function setHeat(h) {
		console.log(`setHeat: ${h}`);
		$priority.surfers = heat.surfers;
		$priority.min = heat.timer;
		$priority.sec = 0;
	}

	async function click(id) {
		let max = $priority.surfers.length;
		console.log($priority.surfers[id]);
		if ($priority.surfers[id].priority === 'P') {
			for (let i in $priority.surfers) {
				if (i != id) {
					let pos = parseInt($priority.surfers[i].priority) - 1;
					if (pos === 1) {
						$priority.surfers[i].priority = 'P';
					} else {
						$priority.surfers[i].priority = pos.toString();
					}
				}
			}
			$priority.surfers[id].priority = max.toString();
		} else if ($priority.surfers[id].priority === '') {
			console.log(`priority empty; pressed: [${id}] ${$priority.surfers[id].priority}`);
			for (let i in $priority.surfers) {
				console.log(`looping(${id}): ${i} - ${$priority.surfers[i].priority}`);
				if (i != id) {
					if ($priority.surfers[i].priority === '') {
						console.log(`empty: [${i}] ${$priority.surfers[i].priority}`);
						continue;
					} else {
						console.log(`not empty: [${i}] ${$priority.surfers[i].priority}`);
						let pos = parseInt($priority.surfers[i].priority) - 1;
						if (pos === 1) {
							$priority.surfers[i].priority = 'P';
						} else {
							$priority.surfers[i].priority = pos.toString();
						}
					}
				}
			}
			$priority.surfers[id].priority = max.toString();
		} else {
			console.log(`pressed: [${id}] ${$priority.surfers[id].priority}`);
			let oldpos = parseInt($priority.surfers[id].priority);
			for (let i in $priority.surfers) {
				if (i != id) {
					console.log(
						`pos: [${i}] ${$priority.surfers[i].priority} ${$priority.surfers[i].priority > oldpos}`
					);
					if ($priority.surfers[i].priority != 'P' && $priority.surfers[i].priority > oldpos) {
						let pos = parseInt($priority.surfers[i].priority);
						if (pos > oldpos) {
							$priority.surfers[i].priority = (pos - 1).toString();
							console.log(`newpos: ${$priority.surfers[i].priority}`);
						}
					}
				} else {
					$priority.surfers[i].priority = max.toString();
					console.log(`last: [${i}] ${$priority.surfers[i].priority}`);
				}
			}
		}
		const res = await fetch(`/api/priority`, {
			method: 'POST',
			body: JSON.stringify({
				priority: $priority.surfers.map((obj) => obj.priority),
				mode: 'priority'
			}),
			headers: {
				'Content-Type': 'application/json'
			}
		});
		console.log(
			JSON.stringify({
				priority: $priority.surfers.map((obj) => obj.priority),
				mode: 'priority'
			})
		);
		console.log(`retval: ${JSON.stringify(res)}`);
	}
</script>

<svelte:window bind:innerWidth={width} />

<div class="header">
	<!-- <button class="button" on:click={() => loadHeats()} disabled={start}>Load</button> -->
	<Select
		options={heats}
		option_label="name"
		bind:value={heat}
		handleSelect={() => setHeat(heat)}
		label="Heats"
		id="heats"
		disabled={$priority.start}
	/>
	{#if !$priority.end}
		<div class="timer">{pad2($priority.min)}:{pad2($priority.sec)}</div>
	{:else}
		<div class="timer" style="color: red">{pad2($priority.min)}:{pad2($priority.sec)}</div>
	{/if}
	{#if $priority.start}
		<Button handleClick={() => stopHeat()} label="STOP" />
	{:else}
		<Button handleClick={() => startHeat()} label="START" />
	{/if}
	<!-- <button class="button" on:click={() => startHeat()} disabled={start}>Start</button> -->
</div>

<div class="container">
	{#each $priority.surfers || [] as surfer, id}
		<div class="box">
			{#if surfer.priority != ''}
				{#if surfer.priority === 'P'}
					{#if surfer.color === 'white'}
						<span class="priority_white">{surfer.priority}</span>
					{:else}
						<span class="priority">{surfer.priority}</span>
					{/if}
				{:else}
					<span class="priority_small">{surfer.priority}</span>
				{/if}
			{/if}
			<div
				class="square"
				{id}
				style="background-color: {surfer.color};"
				on:click={() => click(id)}
				on:contextmenu={(e) => {
					e.preventDefault();
					dblclick(id);
				}}
				on:keypress={console.log('keypress')}
				role="button"
				tabindex={id}
			></div>
			<div class="score">{surfer.score}</div>
		</div>
	{/each}
</div>

<style>
	:root {
		--backColor: #334;
		--textColor: white;
		--maxWidth: (100% - 15px);
	}

	.header {
		display: grid;
		grid-template-columns: repeat(4, 1fr);
		align-items: center;
		justify-content: center;
		/* height: 10vh; */
		background-color: var(--backColor);
		padding-left: 10px;
		padding-right: 10px;
		padding-top: 6px;
		padding-bottom: 6px;
		margin-top: 2px;
		margin-bottom: 2px;
		width: calc(var(--maxWidth));
		color: var(--textColor);
		/* display: flex; */
		/* justify-content: space-between; */
		/* align-items: center; */
	}

	.header .timer {
		grid-column: 3 / 4;
		font-size: 13vh;
		padding-left: 10px;
		padding-right: 20px;
		font-weight: bold;
		flex: 2 2 auto;
		align-self: center;
		text-align: center;
	}

	.container {
		height: 85vh;
		background-color: var(--backColor);
		padding-left: 10px;
		padding-right: 10px;
		padding-top: 4px;
		width: calc(var(--maxWidth));
		color: var(--textColor);
	}

	.box {
		width: 100%;
		display: grid;
		grid-template-columns: repeat(6, 1fr);
		align-items: center;
		padding: 1px;
		margin-bottom: 1px;
	}

	.priority {
		grid-column: 1/1;
		width: 15%;
		height: 100%;
		border-radius: 20%;
		font-size: 8vh;
		/* animation: blink 2s 2; */
		margin-right: auto;
		background-color: white;
		color: black;
		align-items: center;
		justify-content: center;
		font-weight: bold;
	}

	.priority_white {
		width: 15%;
		height: 100%;
		border-radius: 20%;
		font-size: 8vh;
		/* animation: blink_white 2s 3; */
		margin-right: auto;
		background-color: black;
		color: white;
		align-items: center;
		justify-content: center;
		font-weight: bold;
		padding-bottom: 4px;
	}

	.priority_small {
		width: 13%;
		height: 85%;
		border-radius: 20%;
		font-size: 8vh;
		/* animation: blink 2s 3; */
		margin-right: auto;
		margin-left: 30px;
		background-color: #ccc;
		color: black;
		align-items: center;
		justify-content: center;
		font-weight: bold;
	}

	.square {
		grid-column: 2/6;
		width: 100%;
		height: 16vh;
		border-radius: 5px;
		margin-right: 15px;
		align-items: center;
		justify-content: center;
		padding-bottom: 2px;
		margin-bottom: 2px;
	}

	.score {
		padding-right: 20px;
		width: 20%;
		font-size: 12vh;
		float: right;
		text-align: center;
		font-weight: bold;
	}

	@keyframes blink {
		0% {
			background-color: white;
		}
		50% {
			background-color: rgba(255, 255, 255, 0.6);
		}
		100% {
			background-color: white;
		}
	}

	@keyframes blink_white {
		0% {
			background-color: black;
		}
		50% {
			background-color: rgba(0, 0, 0, 0.6);
		}
		100% {
			background-color: black;
		}
	}
</style>
