<script lang="ts">
	import { onDestroy, onMount } from 'svelte';
	import {
		currentDevice,
		type Device,
		pairedDevices,
		pb,
		type RoomData,
		currentUser
	} from '../lib/velconnect';
	import Login from '$lib/components/Login.svelte';
	import Pair from '$lib/components/Pair.svelte';

	if ($currentDevice == '' && $pairedDevices.length > 0) {
		currentDevice.set($pairedDevices[0]);
	}

	let unsubscribeDeviceData: () => void;
	let unsubscribeCurrentDevice: () => void;

	let deviceData: Device | null;
	let roomData: RoomData | null;

	let sending = false;

	$: deviceData,
		() => {
			console.log('Device data changed');
		};

	onMount(async () => {
		if ($currentDevice != '') {
			deviceData = await pb.collection('Device').getOne($currentDevice);
		}

		unsubscribeCurrentDevice = currentDevice.subscribe(async (val) => {
			console.log('current device changed');
			unsubscribeDeviceData?.();
			if (val != '') {
				deviceData = await pb.collection('Device').getOne($currentDevice);
				unsubscribeDeviceData = await pb.collection('Device').subscribe(val, (data) => {
					deviceData = data.record as Device;
				});
			} else {
				deviceData = null;
				roomData = null;
			}
		});
	});

	onDestroy(() => {
		unsubscribeCurrentDevice?.();
		unsubscribeDeviceData?.();
	});

	let abortController = new AbortController();
	function delayedSend() {
		console.log('fn: delayedSend()');

		// abort the previous send
		abortController.abort();
		const newAbortController = new AbortController();
		abortController = newAbortController;
		setTimeout(() => {
			if (!newAbortController.signal.aborted) {
				send();
			} else {
				console.log('aborted');
			}
		}, 1000);
	}

	function send() {
		console.log('sending...');
		sending = true;
		let promises = [];
		if (deviceData) {
			promises.push(pb.collection('Device').update(deviceData.id, deviceData));
		}
		if (roomData) {
			promises.push(pb.collection('DataBlock').update(roomData.id, roomData));
		}
		Promise.all(promises).then(() => {
			sending = false;
		});
	}

	function removeDevice(d: string) {
		pairedDevices.set($pairedDevices.filter((i) => i != d));

		if ($currentDevice == d) {
			console.log('Removed current device');

			// if there are still devices left
			if ($pairedDevices.length > 0) {
				currentDevice.set($pairedDevices[0]);
			} else {
				currentDevice.set('');
			}
		}

		if ($currentUser) {
			$currentUser.devices.filter((i: string) => i != d);
			pb.collection('Users').update($currentUser.id, $currentUser);
		}
	}
</script>

<h1>VEL-Connect</h1>
<img src="/img/velconnect_logo_1.png" alt="logo" width="70px" height="28px" />
<p>
	This is a demo dashboard. Visit the <a href="https://github.com/velaboratory/VEL-Connect"
		>GitHub repo</a
	> to copy it and make your own.
</p>

<Login />
<Pair />

<div>
	<h3>Devices:</h3>
	{#each $pairedDevices as d}
		<div>
			<button
				on:click={() => {
					currentDevice.set(d);
				}}>{d}</button
			>
			<button
				on:click={() => {
					removeDevice(d);
				}}>x</button
			>
		</div>
	{/each}
	{#if $pairedDevices.length == 0}
		<p>No devices paired. Enter a pairing code above.</p>
	{/if}
</div>

{#if sending}
	<div>
		<progress />
	</div>
{/if}

{#if deviceData != null && deviceData.data != null}
	<div>
		<h3>Device Info</h3>

		<device-field>
			<h6>Device ID:</h6>
			<code>{deviceData.id}</code>
		</device-field>
		<device-field>
			<h6>Pairing Code:</h6>
			<code>{deviceData.pairing_code}</code>
		</device-field>
		<device-field>
			<h6>First Seen</h6>
			<p>{deviceData.created}</p>
		</device-field>
		<device-field>
			<h6>Last Seen</h6>
			<p>{deviceData.updated}</p>
		</device-field>
	</div>

	<div>
		<h3>Settings</h3>

		<label>
			User Name
			<input
				type="text"
				placeholder="Enter username..."
				bind:value={deviceData.friendly_name}
				on:input={delayedSend}
			/>
		</label>

		<label>
			Avatar URL
			<a href="https://demo.readyplayer.me" target="blank">
				Create New Avatar
				<svg style="width:1em;height:1em;margin-bottom:-.15em;" viewBox="0 0 24 24">
					<path
						fill="currentColor"
						d="M14,3V5H17.59L7.76,14.83L9.17,16.24L19,6.41V10H21V3M19,19H5V5H12V3H5C3.89,3 3,3.9 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V12H19V19Z"
					/>
				</svg>
			</a>
			<input
				type="text"
				placeholder="https://----.glb"
				bind:value={deviceData.data.avatar_url}
				on:input={delayedSend}
			/>
		</label>

		<device-field>
			<h6>Current Room</h6>
			<a href="/join/{deviceData.current_app}/room_name" target="blank">
				Shareable Link
				<svg style="width:1em;height:1em;margin-bottom:-.15em;" viewBox="0 0 24 24">
					<path
						fill="currentColor"
						d="M14,3V5H17.59L7.76,14.83L9.17,16.24L19,6.41V10H21V3M19,19H5V5H12V3H5C3.89,3 3,3.9 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V12H19V19Z"
					/>
				</svg>
			</a>
			<input
				type="text"
				placeholder="room_1"
				bind:value={deviceData.current_room}
				on:input={delayedSend}
			/>
		</device-field>
	</div>

	<h6>Raw JSON:</h6>
	<pre><code>{JSON.stringify(deviceData, null, 2)}</code></pre>
{/if}

<style lang="scss">
	device-field {
		display: flex;
		flex-direction: column;
		gap: 0em;
		width: fit-content;
		p {
			margin: 0;
		}
	}
</style>
