<script lang="ts">
	import { api_host, authToken } from '$lib';
	import type { AppointmentInputs, AppointmentList, AppointmentTimes, WeekdayAppointment } from '$lib/dbdata';
	import { authFetch, getTimeSlots } from '$lib/funcs';
	import CreatorBaseInputs from '$lib/modules/CreatorBaseInputs.svelte';
	import CreatorInputs from '$lib/modules/CreatorInputs.svelte';
	import CreatorTimeInputs from '$lib/modules/CreatorTimeInputs.svelte';
	import moment from 'moment';
	import { onMount, tick } from 'svelte';

	let creatorInputs: AppointmentInputs[] = [{ name: '', type: 'text' }];
	let topic: string;
	let location: string;
	let selectedWeek: number = 202502;
	let previousWeek: number = selectedWeek;
	let duration: number = 15;
	let dueDate: Date = new Date();
	let description: string = "test";
	let renderTimeSelection: boolean = false;

	let appointmentList: AppointmentList[] = [
		{
			week: selectedWeek,
			appointments: generateAppointments(splitYearAndWeek(selectedWeek).week, splitYearAndWeek(selectedWeek).year),
		}
	];

	function splitYearAndWeek(value: number): { year: number, week: number } {
		const year = Math.floor(value / 100); // Extracts the first 4 digits (year)
		const week = value % 100; // Extracts the last 2 digits (week number)
		return { year, week };
	}

	/**
	 * Generates a JSON structure for a given calendar week with actual dates.
	 * @param weekNumber The calendar week number (1-53).
	 * @param year The year for which the week should be calculated.
	 * @returns An array of objects representing the days of the given week.
	 */
	export function generateAppointments(weekNumber: number, year: number): WeekdayAppointment[] {
		const weekdays = ['Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag'];

		// Get the first day of the given calendar week (Monday-based week system)
		const startOfWeek = moment().year(year).isoWeek(weekNumber).startOf('isoWeek');

		const appointments = weekdays.map((day, index) => ({
			name: day,
			date: startOfWeek.clone().add(index, 'days').format('YYYY-MM-DD'),
			active: false,
			times: []
		}));

		return appointments;
	}

    async function changeWeek() {
		await tick();
        console.log("changed");
		console.log(selectedWeek);
		renderTimeSelection = false;

		/*
		const index = appointmentList.findIndex((entry) => entry.week === selectedWeek);
		if (index !== -1 && selectedWeekAppointments !== undefined) {
			appointmentList[index].appointments = selectedWeekAppointments;
			//console.log(appointmentList[index].appointments);
		}
		*/

        const ix = appointmentList.findIndex((entry) => entry.week === selectedWeek);
		if (ix === -1) {
            const tmp = {
                week: selectedWeek,
                appointments: generateAppointments(splitYearAndWeek(selectedWeek).week, splitYearAndWeek(selectedWeek).year)
            }
            appointmentList = [... appointmentList, tmp];
			selectedWeekAppointments = tmp.appointments;
			console.log("not found");
        } else {
			console.log("test");
			console.log(appointmentList);
			selectedWeekAppointments = appointmentList.find(
				(entry) => entry.week === selectedWeek
			)?.appointments;
			console.log("found and send entry");
		}
		
        
		renderTimeSelection = true;
		previousWeek = selectedWeek;
		//setTimeout(() => renderTimeSelection = false, 2000);
    }

    let selectedWeekAppointments = appointmentList.find(
		(entry) => entry.week === selectedWeek
	)?.appointments;

	$: {
		// deactivate when changing weeks to prevent override
		const ix = appointmentList.findIndex((entry) => entry.week === selectedWeek);
		if (ix !== -1 && selectedWeekAppointments !== undefined && previousWeek === selectedWeek) {
			appointmentList[ix].appointments = selectedWeekAppointments;
			console.log("updated");
			console.log(appointmentList[ix].appointments);
			//renderTimeSelection = true;
			//setTimeout(() => renderTimeSelection = false, 2000);
		}
	}

	function convertAppointmentList() {
		let times: AppointmentTimes[] = [];

		appointmentList.forEach(entry => {
			entry.appointments.filter(element => element.active !== false).forEach(day => {
				day.times.forEach(time => {
					// if (!time.start || !time.end)
					times = [... times, ...getTimeSlots(day.date, time.start, time.end, duration)];
				});
				
			});
		});

		return times;
	}

	async function saveAppointment() {
		if (!topic || !description || !dueDate || !location || !duration || !creatorInputs || !appointmentList) {
			return;
		}
		const convertedTimes: AppointmentTimes[] = convertAppointmentList();
		console.log(convertedTimes);

		try {
            const response = await authFetch(`${api_host}/api/users/create`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "Authorization": "Bearer " + $authToken
                },
                body: JSON.stringify({
                    title: topic,
					description: description,
					dueDate: dueDate,
					place: location,
					duration: duration,
					times: convertedTimes,
					inputs: creatorInputs 
                })
            });

        } catch (error) {
            console.log(error);
        }
	}

	onMount(() => {
		// implement editor if query id param was detected
	});

	// get time slots before sending
</script>

<h3 class="center-align top-padding bottom-padding">Termine</h3>

<fieldset>
	<CreatorBaseInputs changeWeek={changeWeek} bind:topic bind:location bind:selectedWeek bind:duration />

	{#if selectedWeekAppointments}
		{#key renderTimeSelection}
			<CreatorTimeInputs bind:weekdays={selectedWeekAppointments} />	
		{/key}
	{/if}

</fieldset>

<CreatorInputs bind:creatorInputs />

<div class="grid">
	<button on:click={saveAppointment} class="top-margin s12 large">Speichern</button>
</div>

<style>
	fieldset {
		max-width: 90%;
		margin-inline: auto;
	}
</style>
