<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 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;

	let heat = {};

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

	$: min = 0;
	$: sec = 0;
	
	let end = false;

	loadRunning();

	async function loadRunning() {
		const res = await fetch(`/api/runningheat`);
		const data = await res.json();
		heat = data;
		console.log(`retval: ${JSON.stringify(heat)}`);	

		if (heat != null) {
			console.log(`heat: ${JSON.stringify(heat)}`);
			min = heat.timer;
			surfers = heat.surfers;
		}
	}

	// function updateRemainingTime() {
	// 	if ((min === 0) & (sec === 0)) {
	// 		clearInterval(timer);
	// 		end = true;
	// 	} else if (sec === 0) {
	// 		min -= 1;
	// 		sec = 59;
	// 	} else {
	// 		sec -= 1;
	// 	}
	// }

	// updateRemainingTime();

	// const timer = setInterval(updateRemainingTime, 1000);

	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()}`);
		};
	}


	onMount(() => {
        if (!dev) {
            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">
	{#if !end}
		<div class="timer">{pad2(min)}:{pad2(sec)}</div>
	{:else}
		<div class="timer" style="color: red">{pad2(min)}:{pad2(sec)}</div>
	{/if}
</div>

<div class="container">
	{#each surfers as surfer, id}
		<div class="box">
			<div class="square" style="background-color: {surfer.color};">
				{#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;
	}

	.header .timer {
		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);
	}

	.priority {
		width: 90%;
		height: 20%;
		border-radius: 20%;
		font-size: 8vh;
		animation: blink 2s 3;
		margin-top: 50%;
		background-color: white;
		color: black;
		display: flex;
		align-items: center;
		justify-content: center;
		font-weight: bold;
	}

	.priority_white {
		width: 90%;
		height: 20%;
		border-radius: 20%;
		font-size: 8vh;
		animation: blink_white 2s 3;
		margin-top: 50%;
		background-color: black;
		color: white;
		display: flex;
		align-items: center;
		justify-content: center;
        text-align: center;
		font-weight: bold;
		padding-bottom: 4px;
	}
	
	.priority_small {
		width: 80%;
		height: 15%;
		border-radius: 20%;
		font-size: 8vh;
		/* animation: blink 2s infinite; */
		margin-top: 60%;
		margin-left: 20px;
		background-color: #bbb;
		color: black;
		display: flex;
		align-items: center;
		justify-content: center;
		font-weight: bold;
	}	

    .score {
		padding-right: 20px;
		width: 20%;
		font-size: 12vh;
		float: right;
		text-align: center;
		font-weight: bold;
	}
	.box {
		height: 100%;
        width: 19%;
        float: left;
		margin-left: 1px;
        margin-right: 1px;
	}

    .square {
        height: 100%;
        width: 100%;
        float: left;
        align-items: center;
		justify-content: center;
        text-align: center;
    }
</style>
