<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';
	import Number from '$lib/number.svelte';
	import Input from '$lib/input.svelte';
	import Select from '$lib/select.svelte';
	import Color from '$lib/color.svelte';
	import Button from '../../lib/button.svelte';

	$: surfers = 2;
	$: athletes = [];

	$: 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} loadHeats: ${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(`deleteHeat: ${JSON.stringify(res)}`);

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

	async function loadSurfers(category) {
		athletes = [];
		console.log(`load surfer`);
		const res = await fetch(`/api/loadsurfers`);
		const data = await res.json();
		for (let i in data) {
			if (data[i].category === category) {
				athletes.push(data[i]);
				console.log(`${i} loadSurfers: ${JSON.stringify(data[i])}`);
			} 
		}
		athletes = athletes;
		console.log(`category: ${JSON.stringify(athletes)}`);
	}

	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;
		} else {
			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(`save: ${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;
	}

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

<Header title="Heat setup" />

<div class="heat">
	<div class="round">
		<Select label="Round" id="round" bind:value={heat.round} options={$rounds} />
	</div>
	<div class="number">
		<Number label="Number" min="1" max="20" id="number" bind:value={heat.number} />
	</div>
	<div class="category">
		<Select
			label="Category"
			id="category"
			options={$categories}
			bind:value={heat.category}
			handleSelect={loadSurfers(heat.category)}
		/>
	</div>
	<div class="duration">
		<Number label="Duration" id="duration" min="5" max="60" step="5" bind:value={heat.timer} />
	</div>
</div>

<div class="controller">
	<Button handleClick={addSurfers} label="+" />
	<span class="surfers">{surfers}</span>
	<Button handleClick={removeSurfers} label="-" />
</div>

<div class="surfer">
	{#each Array(surfers) as _, surfer}
		<div class="name">
			<Select
				label="Name"
				id="name{surfer}"
				bind:value={surfer_list[surfer].name}
				options={athletes}
				element="firstname"
			/>
			<!-- <Input label="Name" id="name{surfer}" bind:value={surfer_list[surfer].name} /> -->
		</div>
		<div class="color">
			<Color id="color{surfer}" label="Color" bind:value={surfer_list[surfer].color} />
		</div>
	{/each}
</div>

<div class="controller">
	<Button handleClick={save} label="SAVE" />
	<Button handleClick={resetHeat} label="RESET" />
</div>

<hr />
<div class="list">
	{#each heats as h, id}
		<div class="surfer">
			<Button handleClick={() => setHeat(id)} label="{h.round} {h.number} {h.category}" />
			<Button handleClick={() => deleteHeat(id)} label="X" />
		</div>
	{/each}
</div>

<!-- <hr> -->

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

<style>
	.heat {
		background-color: lightgrey;
		display: grid;
		grid-template-columns: repeat(6, 1fr);
		row-gap: 4px;
		font-size: 1.3rem;
		margin-top: 8px;
		margin-bottom: 2px;
		width: 100%;
		margin-left: auto;
		margin-right: auto;
	}

	.round {
		grid-column: 1 / 3;
	}

	.number {
		grid-column: 3 / 6;
	}

	.category {
		grid-column: 1 / 3;
	}

	.duration {
		grid-column: 3 / 6;
	}

	.controller {
		background-color: lightgrey;
	}

	.surfer {
		background-color: lightgrey;
		font-size: 1.3rem;
		margin-top: 2px;
		margin-bottom: 2px;
		/* color: lightcyan; */
		display: grid;
		grid-template-columns: repeat(6, 1fr);
		width: 100%;
		margin-left: auto;
		margin-right: auto;
		border-radius: 8px;
	}

	.name {
		grid-column: 1 / 3;
	}

	.color {
		grid-column: 3 / 6;
	}

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