<script>
	// import { page } from '$app/stores';
	import { onDestroy, onMount } from 'svelte';
	import { dev } from '$app/environment';

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

	let heat_number;
	let heats = [];
	$: surfers = [];
	// 	{ name: 'Kanoa Igarashi', color: 'red', score: '4.50', priority: '3' },
	// 	{ name: 'Griffin Colapinto', color: 'white', score: '5.60', priority: 'P' },
	// 	{ name: 'Jack Robinson', color: 'blue', score: '6.10', priority: '5' },
	// 	{ name: 'Gabriel Medina', color: 'green', score: '4.30', priority: '2' },
	// 	{ name: 'Italo Ferreira', color: 'black', score: '6.50', priority: '4' }
	// ];

	let width;
	// $: activeUrl = $page.url.pathname;

	const pad2 = (number) => `00${number}`.slice(-2);

	$: min = 0;
	$: sec = 0;

	let end = false;
    let start = false;

	loadHeats();

	function Subscribe() {
		const sse = new EventSource(`/api/sse`);
		console.log('subscribe');
		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 surfers) {
					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 (!start) {
					start = true;
				}
			} else if (Msg.mode === 'stop') {
                console.log(`stop duration: ${Msg.duration}`);
                end = true;
                start = false;
            }
		};
		return () => {
			sse.close();
			console.log(`sse closing ${Date.now()}`);
		};
	}

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

    async function startHeat() {
		const res = await fetch(`/api/startheat`, {
			method: 'POST',
			body: JSON.stringify({
				duration: min+"m",
				mode: 'time'
			}),
			headers: {
				'Content-Type': 'application/json'
			}
		});
		console.log(`retval: ${JSON.stringify(res)}`);
        start = true;
        end = false;
    }

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

	function setHeat(id) {
		console.log(`setHeat: ${id}`);
		if (id === "99") {
			min = 0;
			surfers = []
			return;
		}
		min = heats[id].timer;
		surfers = heats[id].surfers;
	}

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

	onMount(() => {
		const unsub = Subscribe();
		return unsub;
	});

	// onDestroy(() => {
	// 	clearInterval(timer); // Pulisci il timer quando il componente viene distrutto
	// });
</script>

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

<div class="header">
	<!-- <button class="button" on:click={() => loadHeats()} disabled={start}>Load</button> -->
	<select name="heats" id="heats" bind:value={heat_number} on:change={() => setHeat(heat_number)}>
		<option value="99">Select Heat</option>			
		{#each heats as heat, id}
			<option value={id}>{heat.name} {heat.number} {heat.category}</option>			
		{/each}
	</select>
	{#if !end}
		<div class="timer">{pad2(min)}:{pad2(sec)}</div>
	{:else}
		<div class="timer" style="color: red">{pad2(min)}:{pad2(sec)}</div>
	{/if}
    <button class="button" on:click={() => startHeat()} disabled={start}>Start</button>
</div>

<div class="container">
	{#each surfers as surfer, id}
		<div class="box">
			<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}
			>
				{#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>
			<div class="score">{surfer.score}</div>
		</div>
	{/each}
</div>

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

	.header {
		/* padding: 15px; */
		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 {
		font-size: 13vh;
		padding-left: 10px;
		padding-right: 20px;
		font-weight: bold;
		flex: 2 2 auto;
		align-self: center;
		text-align: center;
	}

    .header .button {
        height: 60%;
        align-items: center;
        background-color: yellow;
        border-radius: 10%;
    }

	.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: flex;
		align-items: center;
		padding: 1px;
		margin-bottom: 1px;
	}

	.priority {
		width: 15%;
		height: 100%;
		border-radius: 20%;
		font-size: 8vh;
		/* animation: blink 2s 2; */
		margin-right: auto;
		background-color: white;
		color: black;
		display: flex;
		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;
		display: flex;
		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;
		display: flex;
		align-items: center;
		justify-content: center;
		font-weight: bold;
	}

	.square {
		width: 100%;
		height: 16vh;
		border-radius: 5px;
		margin-right: 15px;
		display: flex;
		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>
