import { defineStore } from "pinia";
import dayjs from "dayjs";
import "dayjs/locale/fr";
import { useRouter } from "vue-router";
import { useApiStore } from "./api";

export const useNotificationsStore = defineStore("notifications", () => {
  dayjs.locale("fr");

  const router = useRouter();
  const api = useApiStore();

  function formatDate(notification) {
    const notificationDigitalDate = parseInt(
      dayjs(notification.date).format("YYYYMMDD")
    );
    const todayDigitalDate = parseInt(dayjs().format("YYYYMMDD"));
    const isToday = notificationDigitalDate === todayDigitalDate;

    if (isToday) {
      return dayjs(notification.date).format("HH:mm");
    } else if (todayDigitalDate === notificationDigitalDate + 1) {
      return "hier";
    } else {
      return dayjs(notification.date).format("DD MMM YY");
    }
  }

  function read(notification) {
    if (!notification.id) {
      console.error(
        "Couldn't change notification status because it has no id."
      );
    } else if (notification.isread != true) {
      api
        .readNotification(notification.id)
        .then((res) => {
          console.log(res);
        })
        .catch((err) => console.error("Notification could not be read.", err));
    }
  }

  return { formatDate, read };
});
