<template>
  <article class="comment | flow" :data-status="setStatus(comment)">
    <header>
      <p>
        <strong>{{ comment.author.name ?? comment.author.email }}</strong>
        <template v-if="commentIndex">
          <span class="comment__id">#{{ commentIndex }}</span>
          •
        </template>
        <span class="comment__page">Page {{ comment.file.pageIndex }}</span>
        <time :datetime="dayjs(comment.date).format('YYYY-MM-DD')">{{
          formatDate(comment.date)
        }}</time>
      </p>
    </header>
    <p class="comment__body">
      {{ comment.text }}
    </p>
    <footer v-if="comment.replies?.length > 0" class="comment__replies">
      <span>{{ comment.replies.length }} réponse</span>
    </footer>
  </article>
</template>

<script setup>
import dayjs from "dayjs";
import "dayjs/locale/fr";

dayjs.locale("fr");

const { comment, commentIndex } = defineProps({
  comment: Object,
  commentIndex: Number,
});

//  Functions
function setStatus(comment) {
  try {
    if (!user?.notifications?.comments[comment.id].isRead) {
      return "unread";
    } else {
      return undefined;
    }
  } catch (error) {
    return undefined;
  }
}

function formatDate(date) {
  const todayNumber = parseInt(dayjs().format("YYMMD"));
  const dateNumber = parseInt(dayjs(date).format("YYMMD"));

  if (dateNumber === todayNumber) {
    return "Aujourd'hui";
  }

  if (dateNumber === todayNumber - 1) {
    return "hier";
  }

  return dayjs(date).format("D MMM YY");
}

function closeAddField() {
  isAddOpen.value = false;
  newCommentText.value = "";
}

async function readNotification(notificationId) {
  const newNotifications = await api.readNotification(
    user.uuid,
    "comments",
    notificationId
  );

  user.notifications = newNotifications;
}
</script>
