<script>
    import { onMount } from 'svelte';
    import { surfers, surfersCount } from '$lib/stores/surfers.js';
    import { colors } from '$lib/stores/colors.js';
    import { dev } from '$app/environment';

    if (dev) {
		console.log('Dev mode');
	} else {
		console.log('Not dev mode');
	}

    const events = ['priority'];

    $: start = false;
    // $: surfers_tot = 6;

    let footer_height = 8;
    $: setup_height = ((100 - footer_height) / $surfersCount) - (2.2 / $surfersCount);

	$: if (start && $surfers) {
		window.sessionStorage.setItem('priority', JSON.stringify($surfers));
        window.sessionStorage.setItem('surfers', JSON.stringify($surfersCount));
        window.sessionStorage.setItem('status', JSON.stringify(start));
		console.log(`saved: ${JSON.stringify($surfers)}`);
	}

	onMount(async () => {
		let ses = window.sessionStorage.getItem('priority');        
		if (ses) {
			$surfers = JSON.parse(ses);
            $surfersCount = JSON.parse(window.sessionStorage.getItem('surfers'));
            start = JSON.parse(window.sessionStorage.getItem('status'));
			console.log(`loaded: ${JSON.stringify($surfers)}`);
		}

        if (!dev) {
            const sse = StartSSE();
    		return sse;
        }
	});

    function hasDuplicateColors() {
		const colors = [];

		console.log(JSON.stringify($surfers));

		for (let i = 0; i < $surfersCount; i++) {
			const color = $surfers[i].color;

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

			colors.push(color);
		}

		return false;
	}

    function ResetPriority() {
        for (let i = 0; i < $surfersCount; i++) {
            $surfers[i].priority = '';
        }
    }

    function StartHeat() {
        if (hasDuplicateColors()) {
            alert('Duplicate colors');
            return;
        }
        ResetPriority();
        start = true;
    }

    function StopHeat() {
        window.sessionStorage.clear();
        start = false;
    }

    function AddSurfer() {
        if ($surfersCount < 6) {
            $surfersCount += 1;
        }
    }

    function RemSurfer() {
        if ($surfersCount > 2) {
            $surfersCount -= 1;
        }
    }

    function ResetSurfer() {
        window.sessionStorage.clear(); 
        location.reload();
    }

	 async function ChangePriority(id) {
	 	console.log($surfers[id]);
		if ($surfers[id].priority === 'P') {
			for (let i=0; i<$surfersCount; i++) {
				if (i != id) {
					let pos = parseInt($surfers[i].priority) - 1;
					if (pos === 1) {
						$surfers[i].priority = 'P';
					} else {
						$surfers[i].priority = pos.toString();
					}
				}
			}
			$surfers[id].priority = $surfersCount.toString();
        } else if ($surfers[id].priority === '') {
            console.log(`priority empty; pressed: [${id}] ${$surfers[id].priority}`);
            for (let i=0; i<$surfersCount; i++) { 
                console.log(`looping(${id}): ${i} - ${$surfers[i].priority}`);
                if (i != id) {
                    if ($surfers[i].priority === '') {
                        console.log(`empty: [${i}] ${$surfers[i].priority}`);
                        continue;
                    } else {
                        console.log(`not empty: [${i}] ${$surfers[i].priority}`);
                        let pos = parseInt($surfers[i].priority) - 1;
                        if (pos === 1) {
                            $surfers[i].priority = 'P';
                        } else {
                            $surfers[i].priority = pos.toString();
                        }
                    }
                } 
                $surfers[id].priority = $surfersCount.toString();
            }
        } else {
            console.log(`pressed: [${id}] ${$surfers[id].priority}`);
            let oldpos = parseInt($surfers[id].priority);
            for (let i=0; i<$surfersCount; i++) {
                if (i != id) {
                    console.log(`pos: [${i}] ${$surfers[i].priority} ${$surfers[i].priority > oldpos}`);
                    if ($surfers[i].priority != 'P') {
                        let pos = parseInt($surfers[i].priority);
                        if (pos > oldpos) {
                            console.log(`newpos: ${$surfers[i].priority}`);
                            $surfers[i].priority = (pos - 1).toString();
                        }
                    }
                } else {
                    $surfers[i].priority = $surfersCount.toString();
                    console.log(`last: [${i}] ${$surfers[i].priority}`);
                }
            }
        }

        if (!dev) {
            const res = await fetch(`/api/priority`, {
                method: 'POST',
                body: JSON.stringify({
                    priority: $surfers.map((obj) => obj.priority)
                }),
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            console.log(`retval: ${JSON.stringify(res)}`);
        }	 	
	}

	function StartSSE() {
		let url = '/api/sse?';
		for (let e in events) {
			url += `event=${events[e]}&`;
		}
		console.log(`sse url: ${url}`);
		const sse = new EventSource(url);
		console.log(`subscribe: ${sse}`);

		sse.onopen = () => {
			console.log(`sse open ${now()}`);
		};

		sse.addEventListener('priority', (e) => {
			let Msg = JSON.parse(e.data);
			console.log(JSON.stringify(Msg));
		});


        return () => {
			sse.close();
			console.log(`sse closing ${Date.now()}`);
		};
	}


</script>

{#if start}
    <ul>
        {#each Array($surfersCount) as _, id}
            <li style="--height:{setup_height}vh">
                {#if $surfers[id].priority == 'P'}
                    <div class="priority" id="p" on:click={() => ChangePriority(id)}>{$surfers[id].priority}</div>
                {:else}
                    <div class="priority" id="n" on:click={() => ChangePriority(id)}>{$surfers[id].priority}</div>
                {/if}
                <div class="color" style:background-color={$surfers[id].color}>
                </div>
            </li>        
        {/each}
    </ul>
    <div class="footer" style="--height:{footer_height}vh">
        <button class="button" on:click={StopHeat}>STOP</button>
    </div>    
{:else}
    <ul>
        {#each Array($surfersCount) as _, id}
            <li style="--height:{setup_height}vh">
                <div class="priority" id="color">
                    <select name="color{id}" id="{id}" bind:value={$surfers[id].color} style="background-color: {$surfers[id].color};">
                        {#each $colors as color}
                            <option value="{color}" style="background-color: {color}"></option>
                        {/each}
                    </select>            
                </div>
                <div class="color" style:background-color={$surfers[id].color}></div>
            </li>        
        {/each}
    </ul>
    <div class="footer" style="--height:{footer_height}vh">
        <div class="control">
            <button class="button" on:click={AddSurfer}>+</button>
            <button class="display">{$surfersCount}</button>
            <button class="button" on:click={RemSurfer}>-</button>    
        </div>
        <div class="command">
            <button class="button" on:click={ResetSurfer}>Reset</button>
            <button class="button" on:click={StartHeat}>START</button>    
        </div>
    </div>
{/if}

<style>
	:global(body) {
		overflow-y: hidden;
		overflow-x: hidden;
		margin: 0.2vmin;
		align-content: center;
		justify-content: center;
	}

	a:link,
	a:hover,
	a:visited,
	a:active {
		text-decoration: none;
		color: black;
	}

	ul {
		margin: 0;
		padding: 0;
	}

	li {
		display: flex;
		flex-direction: row;
		margin-top: 0.2vh;
		margin-bottom: 0.2vh;
		overflow: hidden;
        height: var(--height);
	}

	.priority {
		text-align: center;
		align-self: center;
		min-height: var(--height);
		min-width: var(--height);
		margin-right: 0.2vw;
		background-color: gray;
	}

	.priority#p {
		font-size: 16vmin;
		background-color: lightgray;
		height: 100%;
	}

	.priority#n {
		font-size: 14vmin;
		height: 100%;
	}

    .priority#color {
        background-color: lightgrey;
        margin: 0 auto;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .priority#color select {
        width: 100%;
        /* margin-top: 40%; */
        font-size: 6vmin;
    }

	.color {
		width: 100vw;
	}

    .footer {
        display: inline-flex;
        bottom: 0;
        background-color: darkgrey;
        /* border: 2px solid black; */
        width: 100%;        
        height: var(--height);
        justify-content: center;
        align-items: center;
    }

    .control {
        margin-left: 0;
        margin-right: auto;
    }

    .command {
        margin-left: auto;
        margin-right: 0;
    }

    .display {
        margin-left: 2vmin;
        margin-right: 2vmin;
        font-size: 2.5vmin;
    }

    .button {
        margin-left: 2vmin;
        margin-right: 2vmin;
        border-radius: 4px;
        border-style: inset;
        font-size: 2.5vmin;
    }
</style>
