<script setup lang="ts">
import { onBeforeMount, ref } from 'vue';

const rooms = ref();
const showRooms = ref<boolean>(false);
const weekNumber = ref<number>(1);

async function getData() {
    showRooms.value = false;
    const today = new Date();
    if (today.getDay() == 0 || today.getDay() == 6) {
        return;
    }
    const day = today.getDay() * weekNumber.value;
    const res = await fetch("/currentRooms", {
        method: "POST",
        body: JSON.stringify({day: day}),
        headers: new Headers({'content-type': 'application/json'})
    });
    if (res.ok) {
        rooms.value = await res.json();
        showRooms.value = true;
        return;
    }
    console.log(await res.text());
}

defineEmits(['addSlot']);
onBeforeMount(async () => {
    await getData();
});
</script>
<template>
    <header>
        <h1>What's free in my free?</h1>
        <button @click="$emit('addSlot')">Add new slot</button> <br>
        <select v-model="weekNumber" @change="getData">
            <option :value="1">1</option>
            <option :value="2">2</option>
        </select>
    </header>
    <article>
        <h2>Free Rooms:</h2>
        <p v-if="!showRooms">No free rooms right now</p>
        <ul v-else v-for="slot in rooms.records">
            <li>Room: {{ slot.RoomName }}, in {{ slot.Period }}</li>
        </ul>
    </article>
</template>