<script lang="ts">
	import type { Application } from '$lib/ApplicationsStore.svelte';
	import { post, preventDefault } from '$lib/utils';

	let {
		dialog = $bindable(),
		openWindow = $bindable(),
		onreload,
		id
	}: {
		dialog: HTMLDialogElement;
		onreload: (item: Application) => void;
		id: string;
		openWindow?: Window | null;
	} = $props();

	const data = $state({
		url: ''
	});

	let form: HTMLFormElement | undefined = $state();

	async function submit() {
		try {
			const newItem = await post('application/update/url', {
				id,
				...data
			});
			data.url = '';
			dialog.close();
			onreload(newItem);
		} catch (e) {
			// Show message to the user
			console.log(e);
		}
	}

	let hasExtension = $state(false);

	$effect(() => {
		function onMessage(e: MessageEvent) {
			if (e.data.type === 'MY_GET_URL_R') {
				if (e.data.error) {
					console.log(e.data);
					if (e.data.data.length === 0) {
						console.log('TODO inform user to mark page');
					} else {
						console.log('TODO inform use to unmark page');
					}
					return;
				}
				data.url = e.data.url ?? '';
				window.requestAnimationFrame(() => {
					if (!form?.reportValidity()) {
						return;
					}
					submit();
				});
			} else if (e.data.type === 'HAS_EXTENSION') {
				hasExtension = true;
				console.log('got ext');
			}

			if (!hasExtension) {
				window.postMessage({ type: 'HAS_EXTENSION_Q' });
			}
		}

		console.log('setting up');

		window.addEventListener('message', onMessage);
		return () => {
			window.removeEventListener('message', onMessage);
		};
	});

	function askForUrl() {
		console.log('sending');
		window.postMessage({ type: 'MY_GET_URL' });
	}
</script>

<dialog class="card" bind:this={dialog}>
	<form bind:this={form} onsubmit={preventDefault(submit)}>
		<fieldset>
			<label class="flabel" for="text">Url</label>
			<textarea class="finput min-w-96 min-h-96" id="text" bind:value={data.url}></textarea>
		</fieldset>
		<div class="btns">
			<button type="submit" class="btn-confirm">Update</button>
			{#if hasExtension}
				<button type="button" class="btn-confirm" onclick={askForUrl}>Get Url</button>
			{/if}
		</div>
	</form>
</dialog>
