<!--
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 setup lang="ts">
import moduleStore from "@/store/moduleStore.ts";
import { createIndividualFeed } from "@/api/createFeed.ts";
import { router } from "@/main";
import tokenStore from "@/store/tokenStore.ts";
import { Ref, computed, inject, ref, onMounted } from "vue";
import ModuleTemplateDialog from "@/components/ModuleTemplateDialog.vue";
import { onlyWhitespace } from "@/helpers/strings.ts";
import { useI18n } from "vue-i18n";
import { Module } from "@/model/module.ts";
import { useToast } from "primevue/usetoast";
const { t } = useI18n({ useScope: "global" });

const store = moduleStore();
const tableData: Ref<{ Course: string; Module: Module }[]> = ref([
  { Course: "", Module: {} as Module },
]);

onMounted(
  () =>
    (tableData.value = store.getAllModules().map((module) => {
      return {
        Course: module.course,
        Module: module,
      };
    })),
);

const mobilePage = inject("mobilePage") as Ref<boolean>;

const columns = computed(() => [
  { field: "Course", header: t("moduleInformation.course") },
  { field: "Module", header: t("moduleInformation.module") },
  { field: "Reminder", header: t("renameModules.reminder") },
]);

const toast = useToast();
const requestIsPending = ref(false);

async function finalStep() {
  requestIsPending.value = true;
  const createFeed: Promise<string> = createIndividualFeed(
    store.getAllModules(),
  );

  // Check if createFeed Promise is resolved
  createFeed.then(async (token: string) => {
    tokenStore().setToken(token);
    requestIsPending.value = false;
    await router.push("/calendar-link");
  });

  // if createFeed Promise is rejected
  createFeed.catch(() => {
    toast.add({
      severity: "error",
      summary: t("renameModules.error"),
      detail: t("renameModules.TooManyRequests"),
      life: 3000,
    });
  });
}
</script>

<template>
  <div class="flex flex-column align-items-center mb-7">
    <div class="flex align-items-center justify-content-center m-2 gap-2">
      <h3>{{ $t("renameModules.subTitle") }}</h3>
      <ModuleTemplateDialog />
    </div>
    <div class="w-full lg:w-8 flex flex-column">
      <div class="card flex align-items-center justify-content-center my-2">
        <DataTable
          :value="tableData"
          edit-mode="cell"
          table-class="editable-cells-table"
          responsive-layout="scroll"
          :size="mobilePage ? 'small' : 'large'"
          class="w-full"
        >
          <template #header>
            <div
              class="flex align-items-center justify-content-end flex-wrap gap-2 px-2"
            >
              {{ $t("renameModules.enableAllNotifications") }}
              <InputSwitch
                :model-value="
                  tableData.reduce(
                    (acc, curr) => acc && curr.Module.reminder,
                    true,
                  )
                "
                @update:model-value="
                  tableData.forEach(
                    (module) => (module.Module.reminder = $event),
                  )
                "
              />
            </div>
          </template>
          <Column
            v-for="(item, index) in columns"
            :key="index"
            :field="item.field"
            :header="item.header"
            :class="item.field === 'Reminder' ? 'text-center' : ''"
          >
            <!-- Text Body -->
            <template #body="{ data, field }">
              <template v-if="field === 'Module'">
                {{
                  onlyWhitespace(data[field].userDefinedName)
                    ? data[field].name
                    : data[field].userDefinedName
                }}
              </template>
              <template v-else-if="field === 'Reminder'">
                <div class="flex align-items-start">
                  <Button
                    icon="pi pi-bell"
                    :severity="data.Module.reminder ? 'warning' : 'secondary'"
                    rounded
                    outlined
                    class="small-button"
                    @click="data.Module.reminder = !data.Module.reminder"
                  />
                </div>
              </template>
              <template v-else>
                {{ data[field] }}
              </template>
            </template>
            <!-- Editor Body -->
            <template #editor="{ data, field }">
              <template v-if="field === 'Module'">
                <InputText
                  v-model="data[field].userDefinedName"
                  class="w-full"
                  autofocus
                />
              </template>
              <template v-else-if="field === 'Reminder'">
                <div class="flex align-items-start">
                  <Button
                    icon="pi pi-bell"
                    :severity="data.Module.reminder ? 'warning' : 'secondary'"
                    rounded
                    outlined
                    class="small-button"
                    @click="data.Module.reminder = !data.Module.reminder"
                  />
                </div>
              </template>
              <template v-else>
                <div>{{ data[field] }}</div>
              </template>
            </template>
          </Column>
        </DataTable>
      </div>

      <Button
        :disabled="store.isEmpty() || requestIsPending"
        class="col-12 md:col-4 mb-3 align-self-end"
        :icon="requestIsPending ? 'pi pi-spin pi-spinner' : 'pi pi-save'"
        :label="$t('renameModules.nextStep')"
        @click="finalStep()"
      />
    </div>
  </div>
</template>

<style scoped></style>
