<script lang="ts">
	import type { Appointment, AppointmentInputs, DynamicJson } from '$lib/dbdata';
	import { extractTime, toLocalDTSTAMP } from '$lib/funcs';
	import moment from 'moment';
	import AppointmentInfo from './AppointmentInfo.svelte';
	import AppointmentRegisterInputs from './AppointmentRegisterInputs.svelte';
	import { createEvent } from 'ics';

	export let active: boolean;

	export let appointment: Appointment;
	export let date: Date = new Date();
	export let dynamicInputs: DynamicJson[] = [];

	let errorMessage: string = '';
	let successMessage: string = '';
	let enableICSDownload: boolean = false;

	let time: string = '00:00';

	function createEventICS() {
		const formattedDate: string = toLocalDTSTAMP(moment.utc(date.toLocaleString()));
		console.log(formattedDate);

		createEvent(
			{
				title: appointment.title,
				description: appointment.description,
				busyStatus: 'BUSY',
        start: formattedDate,
				duration: { minutes: appointment.duration }
			},
			(error, value) => {
				if (error) {
					console.log(error);
				}
				const blob = new Blob([value], { type: 'text/calendar' });
        const url = window.URL.createObjectURL(blob);

        setTimeout(() => {
            window.location.href = url; // Triggers opening on supported devices
        }, 1000);
		});
	}

	$: {
		time = extractTime(new Date(date));
	}
</script>

<dialog class="max {active ? 'active' : ''}">
	<div class="center medium-padding">
		<AppointmentInfo
			bind:title={appointment.title}
			bind:location={appointment.place}
			bind:description={appointment.description}
			bind:duration={appointment.duration}
			bind:time
			bind:date
			isConfirmation={true}
		/>

		<AppointmentRegisterInputs
			bind:modalActive={active}
      bind:booked={enableICSDownload}
			bind:errorMessage
			bind:successMessage
			bind:date
			bind:appointmentId={appointment._id}
			bind:dynamicInputs
		/>
	</div>

  {#if enableICSDownload && false}
    <button class="responsive green" on:click={createEventICS}>Download ICS</button>
  {/if}
</dialog>


{#if errorMessage}
	<div class="snackbar error active">{errorMessage}</div>
{/if}


{#if successMessage}
	<div class="snackbar green active">{successMessage}</div>
{/if}
