<script>
	import { onMount } from 'svelte';
	import Header from '$lib/header-setup.svelte';
	import Button from '$lib/button.svelte';
	import Select from '$lib/select.svelte';
	import Input from '$lib/input.svelte';
	import { categories } from '$lib/stores/categories.js';

	$: surfers = [];

	let surfer = {};

	$: value = '';

	function resetSurfer() {
		surfer = {
			firstname: '',
			lastname: '',
			name: '',
			category: ''
		};
	}

	async function loadSurfers() {
		const res = await fetch(`/api/loadsurfers`);
		const data = await res.json();
		for (let i in data) {
			const flname = data[i].name.split(" ");
			data[i].firstname = flname[0];
			data[i].lastname = flname[1];
			surfers[i] = data[i];
			
			console.log(`${i} retval: ${JSON.stringify(data[i])}`);
		}
	}

	async function save() {
		if (surfer.firstname === '') {
			alert('Must have a name');
			return;
		}

		if (surfer.lastname === '') {
			alert('Must have a name');
			return;
		}

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

		surfer.name = `${surfer.firstname} ${surfer.lastname}`

		const res = await fetch(`/api/savesurfer`, {
			method: 'POST',
			body: JSON.stringify(surfer),
			headers: {
				'Content-Type': 'application/json'
			}
		});

		console.log(`retval: ${JSON.stringify(res)}`);
		console.log(JSON.stringify(surfer));

		resetSurfer();
		loadSurfers();
	}

	onMount(() => {
		resetSurfer();
		loadSurfers();
	});
</script>

<Header title="Surfer Edit" />

<div class="form">
	<Input label="Firstame" id="firstname" bind:value={surfer.firstname} />
	<Input label="Lastname" id="lastname" bind:value={surfer.lastname} />
	<Select label="category" id="category" options={$categories} bind:value={surfer.category} />
</div>

<Button handleClick={save} label="SAVE"></Button>
<Button handleClick={resetSurfer} label="Reset"></Button>

<hr />

<label for="surfer">{JSON.stringify(surfer)}</label>

<hr />

{#each surfers as s}
	<label for={s}>{s.firstname} {s.lastname} - {s.category}</label><br />
{/each}}
