<!--
Calendar implementation for the HTWK Leipzig timetable. Evaluation and display of the individual dates in iCal format.
Copyright (C) 2024 HTWKalender support@htwkalender.de

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
-->

<script lang="ts" setup>
import { Ref, computed, ref, watch } from "vue";
import { fetchRoom } from "@/api/fetchRoom.ts";
import DynamicPage from "@/view/DynamicPage.vue";
import RoomOccupation from "@/components/RoomOccupation.vue";
import { computedAsync } from "@vueuse/core";
import { router } from "@/main";
import { useI18n } from "vue-i18n";
import { useToast } from "primevue/usetoast";
import { getLink } from "@/helpers/url.ts";
const { t } = useI18n({ useScope: "global" });
const toast = useToast();

const show = () => {
  toast.add({
    severity: "info",
    summary: t("calendarLink.copyToastSummary"),
    detail: t("calendarLink.copyToastNotification"),
    life: 3000,
  });
};

const failedClipboard = () => {
    toast.add({
      severity: "error",
      summary: t("calendarLink.copyToastError"),
      detail: t("calendarLink.copyToastErrorDetail"),
      life: 3000,
    });
};

type Room = {
  name: string;
};

const selectedRoom: Ref<Room> = ref({ name: "" });

// Watch for changes in URL parameter
router.afterEach(async (to) => {
  const room = to.query.room;
  if (room && typeof room === "string") {
    setRoomFromList(room, rooms.value);
  }
});

const rooms = computedAsync<Set<string>>(async () => {
  let rooms: Set<string> = new Set();
  return await fetchRoom()
    .then((data) => {
      rooms = new Set(data);
      return rooms;
    })
    .finally(() => {
      const room = router.currentRoute.value.query.room;
      if (room && typeof room === "string") {
        // check if room is available in roomsList
        setRoomFromList(room, rooms);
      }
    });
}, new Set());

const roomsList = computed(() => {
  return Array.from(rooms.value).map((room) => {
    return { name: room } as Room;
  });
});

/**
 * Set the room from the list of rooms
 * @param room Name of the room
 * @param rooms List of available rooms
 */
function setRoomFromList(room: string, rooms: Set<string>) {
  // wait for the roomsList to be available
  const roomInList: boolean = rooms.has(room);
  if (roomInList) {
    selectedRoom.value.name = room;
  }
}

watch(selectedRoom, (newRoom: Room) => {
  if (newRoom.name !== "") {
    router.push({
      query: { ...router.currentRoute.value.query, room: newRoom.name },
    });
  }
});


const button = computed(() => {
  return {
    label: t("roomFinderPage.roomIcal") + selectedRoom.value.name,
    icon: "pi pi-clone",
    disabled: selectedRoom.value.name === "",
    onClick: () => {
      // Copy iCal link to clipboard
      // localhost/api/feed/room?id=selectedRoom.value.name
      navigator.clipboard.writeText(getLink("/api/feed/room?id=",  selectedRoom.value.name)).then(() => show(), () => failedClipboard())
    },
  };
});

</script>

<template>
  <DynamicPage
    :hide-content="selectedRoom.name === ''"
    :headline="t('roomFinderPage.headline')"
    :sub-title="t('roomFinderPage.detail')"
    icon="pi pi-search"
    :lower-button="button"
  >
    <template #selection>
      <Dropdown
        v-model="selectedRoom"
        :options="roomsList"
        class="flex-1 m-0"
        filter
        option-label="name"
        :placeholder="t('roomFinderPage.dropDownSelect')"
        :empty-message="t('roomFinderPage.noRoomsAvailable')"
        :auto-filter-focus="true"
      />
    </template>
    <template #content>
      <RoomOccupation :room="selectedRoom.name" />
    </template>
      <Button
        class="col-12 md:col-4 mt-3"
        :label="t('roomFinderPage.reset')"
        @click="selectedRoom.name = ''"
      />
  </DynamicPage>
</template>
