<script>
    import { onMount } from 'svelte';
    import Logo from "$lib/img/topscorer_logo_web.png"

    let colors = [
        "black",
        "blue",
        "red",
        "green",
        "yellow",
        "pink",
        "white",
    ];

    let rounds = [
        "Qualifying",
        "Opening",
        "Elimination",
        "Round of 48",
        "Round of 32",
        "Round of 16",
        "Quarterfinal",
        "Semifinal",
        "Final",
    ];

    let categories = [
        "Under 12 Women",
        "Under 12 Men",
        "Under 14 Women",
        "Under 14 Men",
        "Under 16 Women",
        "Under 16 Men",
        "Under 18 Women",
        "Under 18 Men",
    ];

    $: 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,
            name: '',
            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.name = heats[id].name;
        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({
            name: '',
            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.name === '') {
            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>

<div class="header">
    <img class="img" src={Logo} alt="logo">
    <span class="title" style="color: aliceblue;">Heat setup</span>
</div>

<div class="container">    
    <div class="heat">
            <label class="label" for="heat">Heat</label>
            <select name="heat" id="heat" bind:value={heat.name}>
                {#each rounds as round}
                    <option value={round}>{round}</option>
                {/each}
            </select>
            <!-- <input bind:value={heat.name} on:change={capitalize(heat, "name")} id="name" type="text"> -->
            <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>
            <!-- <input bind:value={heat.category} on:change={capitalize(heat, "category")} id="category" type="text"> -->
            <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>

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

    {#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.name} {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 {
        display: block;
    }

    .header {
        background-color: black;
        display: flex;        
        width: 100%;
        justify-content: space-between;
        text-align: center;
        align-items: center;
    }

    .header .img {
        height: 3rem;
    }

    .header .title {
        font-size: 3rem;        
        margin: 0 auto;
    }

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

    .heat {
        font-size: 1.3rem;
        margin-top: 8px;
        margin-bottom: 2px;
        width: 100%;
        margin-left: auto;
        margin-right: auto;
        /* color: lightcyan; */
        display: inline-block;        
    }

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


    .surfer {
        font-size: 1.3rem;
        margin-top: 2px;
        margin-bottom: 2px;
        /* color: lightcyan; */
        display: inline-flex;
        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>