<script lang="ts" setup>
import tokenStore from "../store/tokenStore.ts";
import { useToast } from "primevue/usetoast";
import {computed, onMounted} from "vue";
import router from "../router";
import { useI18n } from "vue-i18n";
const { t } = useI18n({ useScope: "global" });

const toast = useToast();

const domain = window.location.hostname;

const getLink = () =>
  "https://" + domain + "/api/feed?token=" + tokenStore().token;

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

onMounted(() => {
  rerouteIfTokenIsEmpty();
});

function rerouteIfTokenIsEmpty() {
  if (tokenStore().token == "") {
    router.push("/");
  }
}

function copyToClipboard() {
  // Copy the text inside the text field
  navigator.clipboard.writeText(getLink()).then(show, (err) => {
    console.error("Could not copy text: ", err);
    toast.add({
      severity: "error",
      summary: t("calendarLink.copyToastError"),
      detail: t("calendarLink.copyToastErrorDetail"),
      life: 3000,
    });
  });
}

const forwardToGoogle = () => {
  window.open(
    "https://calendar.google.com/calendar/u/0/r?cid=" +
      encodeURI(getLink().replace("https://", "http://")),
  );
};

const forwardToMicrosoft = () => {
  window.open(
    "https://outlook.live.com/owa?path=/calendar/action/compose&rru=addsubscription&name=HTWK%20Kalender&url=" +
      encodeURI(getLink()),
  );
};

const actions = computed(() => [
  {
    label: t("calendarLink.copyToClipboard"),
    icon: "pi pi-copy",
    command: copyToClipboard,
  },
  {
    label: t("calendarLink.toGoogleCalendar"),
    icon: "pi pi-google",
    command: forwardToGoogle,
  },
  {
    label: t("calendarLink.toMicrosoftCalendar"),
    icon: "pi pi-microsoft",
    command: forwardToMicrosoft,
  },
]);
</script>

<template>

  <div class="flex flex-column">
    <div class="flex align-items-center justify-content-center h-4rem m-2">
      <h2>
        {{ getLink() }}
      </h2>
    </div>
    <div class="flex align-items-center justify-content-center m-2">
      <Menu :model="actions" />
    </div>
  </div>
</template>

<style scoped></style>
