<script>
	import { onMount } from 'svelte';
	import Header from '$lib/header-setup.svelte';
	import { categories } from '$lib/stores/categories.js';
	import { rounds } from '$lib/stores/rounds.js';
	import { colors } from '$lib/stores/colors.js';

	$: surfers = 2;

	$: heats = [];
	let surfer_list = [];
	$: heat = {};

	resetHeat();
	loadHeats();

	function resetHeat() {
		surfers = 2;
		surfer_list = new Array();
		surfer_list.push({
			name: '',
			color: '',
			score: '',
			priority: ''
		});
		surfer_list.push({
			name: '',
			color: '',
			score: '',
			priority: ''
		});

		heat = {
			number: 1,
			round: '',
			category: '',
			timer: 20,
			surfers: surfer_list
		};
	}

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

	async function deleteHeat(id) {
		const res = await fetch(`/api/deleteheat`, {
			method: 'POST',
			body: JSON.stringify(heats[id]),
			headers: {
				'Content-Type': 'application/json'
			}
		});
		console.log(`retval: ${JSON.stringify(res)}`);

		console.log(JSON.stringify(heats[id]));
		resetHeat();
		loadHeats();
	}

	function setHeat(id) {
		resetHeat();
		console.log(`setHeat: ${id}`);
		console.log(heats[id]);
		heat.number = heats[id].number;
		heat.round = heats[id].round;
		heat.category = heats[id].category;
		heat.timer = heats[id].timer;
		surfer_list = heats[id].surfers;
		surfers = surfer_list.length;
	}

	function addSurfers() {
		surfers++;
		surfer_list.push({
			round: '',
			color: '',
			score: '',
			priority: ''
		});
	}

	function removeSurfers() {
		surfers--;
		if (surfers < 2) surfers = 2;
		surfer_list.pop();
	}

	async function save() {
		if (hasDuplicateColors(surfer_list)) {
			alert('Colors must be unique');
			return;
		}

		if (surfer_list.length < 2) {
			alert('Must have at least 2 surfers');
			return;
		}

		if (heat.round === '') {
			alert('Must have a name');
			return;
		}

		if (heat.category === '') {
			alert('Must have a category');
			return;
		}

		if (heat.number === '') {
			alert('Must have a number');
			return;
		}

		if (heat.timer === '') {
			alert('Must have a timer');
			return;
		}

		heat.surfers = surfer_list;

		const res = await fetch(`/api/saveheat`, {
			method: 'POST',
			body: JSON.stringify(heat),
			headers: {
				'Content-Type': 'application/json'
			}
		});
		console.log(`retval: ${JSON.stringify(res)}`);

		console.log(JSON.stringify(heat));

		resetHeat();
		loadHeats();
	}

	function hasDuplicateColors(arr) {
		const colors = [];

		console.log(JSON.stringify(arr));

		for (let i = 0; i < arr.length; i++) {
			const color = arr[i].color;

			if (colors.includes(color)) {
				console.log(`duplicate color: ${color}`);
				return true;
			}

			colors.push(color);
		}

		return false;
	}

	function capitalize(element, elementName) {
		element[elementName] =
			element[elementName].charAt(0).toUpperCase() + element[elementName].slice(1);
		console.log(`element: ${element[elementName]}`);
	}

	onMount(() => {
		resetHeat();
		loadHeats();
	});
</script>

<Header title="Heat setup" />

<div class="container">
	<div class="heat">
		<label class="label" for="round">Round</label>
		<select name="round" id="round" bind:value={heat.round}>
			{#each $rounds as round}
				<option value={round}>{round}</option>
			{/each}
		</select>
		<label class="label" for="number">Number</label>
		<input bind:value={heat.number} id="number" type="number" min="1" max="20" />
		<label class="label" for="category">Category</label>
		<select name="category" id="category" bind:value={heat.category}>
			{#each $categories as category}
				<option value={category}>{category}</option>
			{/each}
		</select>
		<label class="label" for="timer">Duration</label>
		<input bind:value={heat.timer} id="timer" type="number" min="5" max="60" step="5" />
		<!-- on:keydown={(event) => {event.preventDefault()}} -->
	</div>

	<hr />
	<div class="controller">
		<button
			class="plus"
			on:click={() => {
				addSurfers();
			}}>+</button
		>
		<span class="surfers">{surfers}</span>
		<button
			class="plus"
			on:click={() => {
				removeSurfers();
			}}>-</button
		>
	</div>

	{#each Array(surfers) as _, surfer}
		<div class="surfer">
			<label class="label" for="name{surfer}">Name</label>
			<input
				bind:value={surfer_list[surfer].name}
				on:change={capitalize(surfer_list[surfer], 'name')}
				id="name{surfer}"
				type="text"
			/>
			<label class="label" for="color{surfer}">Color</label>
			<select
				name="color"
				id="color{surfer}"
				bind:value={surfer_list[surfer].color}
				style="background-color: {surfer_list[surfer].color};"
			>
				{#each $colors as color}
					<option value={color} style="background-color: {color};">{color}</option>
				{/each}
				<!-- <option value="red" style="background-color: red;">Select color</option> -->
				<!-- <option value="red" style="background-color: red;">Red</option>
                <option value="blue" style="background-color: blue;">Blue</option>
                <option value="green" style="background-color: green;">Green</option>
                <option value="yellow" style="background-color: yellow;">Yellow</option>
                <option value="orange" style="background-color: orange;">Orange</option>
                <option value="violet" style="background-color: violet;">Violet</option>                 -->
			</select>
			<!-- <input bind:value={surfer_list[surfer].color} type="color" id="color{surfer}"> -->
		</div>
	{/each}
</div>

<button
	class="plus"
	on:click={() => {
		save();
	}}>SAVE</button
>
<button
	class="plus"
	on:click={() => {
		resetHeat();
	}}>RESET</button
>
<hr />
{#each heats as h, id}
	<div class="surfer">
		<button
			on:click={() => {
				setHeat(id);
			}}>{h.round} {h.number} {h.category}</button
		>
		<button
			class="plus"
			on:click={() => {
				deleteHeat(id);
			}}>X</button
		>
	</div>
{/each}

<!-- <hr> -->

<!-- <h2>{JSON.stringify(surfer_list)}</h2> -->

<style>
	.container {
		background-color: lightgrey;
	}

	.heat {
		display: grid;
		grid-template-columns: auto 2fr auto 2fr;
		font-size: 1.3rem;
		margin-top: 8px;
		margin-bottom: 2px;
		width: 100%;
		margin-left: auto;
		margin-right: auto;
	}

	.heat input {
		font-size: 1.2rem;
		border-radius: 6px;
		margin-left: 0.1rem;
		margin-right: 0.1rem;
		padding-top: 2px;
		padding-bottom: 2px;
	}

	.heat select {
		font-size: 1.2rem;
		border-radius: 6px;
		margin-left: 0.1rem;
		margin-right: 0.1rem;
		padding-top: 2px;
		padding-bottom: 2px;
	}

	.label {
		border: 2px solid #555;
		background-color: gray;
		border-radius: 8px;
		padding: 2px;
	}

	.surfer {
		font-size: 1.3rem;
		margin-top: 2px;
		margin-bottom: 2px;
		/* color: lightcyan; */
		display: grid;
		grid-template-columns: auto auto auto auto;
		width: 100%;
		margin-left: auto;
		margin-right: auto;
		border-radius: 8px;
	}

	.surfer input {
		font-size: 1.2rem;
		border-radius: 6px;
		margin-left: 0.1rem;
		margin-right: 0.1rem;
		padding-top: 2px;
		padding-bottom: 2px;
	}

	.surfer select {
		font-size: 1.2rem;
	}

	.plus {
		border-radius: 8px;
		margin-left: 0.2rem;
		margin-right: 0.2rem;
		margin-bottom: 8px;
		margin-top: 8px;
	}

	.surfers {
		border: 1px solid #111;
		background-color: yellow;
		border-radius: 8px;
		padding: 5px;
	}
</style>
