<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: '',
			category: ''
		};
	}

	async function loadSurfers() {
		surfers = [];
		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];
			surfers = surfers;
			console.log(`${i} retval: ${JSON.stringify(data[i])}`);
		}
	}

	async function deleteSurfer(surfer) {
		console.log(`deleting: ${JSON.stringify(surfer)}`);
		const res = await fetch(`/api/deletesurfer`, {
			method: 'POST',
			body: JSON.stringify(surfer),
			headers: {
				'Content-Type': 'application/json'
			}
		});

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

	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({
				name: `${surfer.firstname}.${surfer.lastname}`,
				category: surfer.category
			}),
			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 />

{#each surfers as s}
	<Button label="{s.firstname} {s.lastname} - {s.category}" />
	<Button handleClick={() => deleteSurfer(s)} label="X" />
	<br />
{/each}}
