<template>
  <div>
    <button
      v-if="idsMarkedAsRead.length === 0"
      class="btn btn-primary"
      type="button"
      @click="markAllRead"
    >
      <i class="fa fa-sm fa-envelope-open-o"></i> Marquer tout comme lu
    </button>
    <button v-else class="btn btn-primary" type="button" @click="undo">
      <i class="fa fa-sm fa-envelope-open-o"></i> Annuler
    </button>
  </div>
</template>

<script lang="ts" setup>
import { makeFetch } from "../../../lib/api/apiMethods";
import { ref } from "vue";

const emit = defineEmits<{
  (e: "markAsRead", id: number): void;
  (e: "markAsUnRead", id: number): void;
}>();

const idsMarkedAsRead = ref([] as number[]);

async function markAllRead() {
  const ids: number[] = await makeFetch(
    "POST",
    `/api/1.0/main/notification/mark/allread`,
    null,
  );
  for (let i of ids) {
    idsMarkedAsRead.value.push(i);
    emit("markAsRead", i);
  }
}

async function undo() {
  const touched: number[] = await makeFetch(
    "POST",
    `/api/1.0/main/notification/mark/undoallread`,
    idsMarkedAsRead.value,
  );
  while (idsMarkedAsRead.value.length > 0) {
    idsMarkedAsRead.value.pop();
  }
  for (let t of touched) {
    emit("markAsUnRead", t);
  }
}
</script>

<style lang="scss" scoped></style>
