<script setup lang="ts">
import { ref, onMounted, onBeforeUpdate } from "vue";

import axios from "axios";
import MarkdownRender from "./markdown/MarkdownRender.vue";

const props = defineProps<{
  path: string;
  order?: number;
}>();

const loadedPage = ref("");
const markdown = ref("");

function refresh() {
  const markdownFileUrl = `/${props.path}.md`;
  if (loadedPage.value === markdownFileUrl) {
    return;
  }
  loadedPage.value = markdownFileUrl;
  console.log(`Chargement de l'URL ${markdownFileUrl}`);
  axios
    .get(markdownFileUrl)
    .then((response) => {
      markdown.value = response.data;
    })
    .catch(
      () =>
        (markdown.value =
          "# 404 Not Found \n \n La page recherchée n'a pas pu être trouvée")
    );
}

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

onBeforeUpdate(() => {
  refresh();
});
</script>

<template>
  <article>
    <MarkdownRender
      :markdown="markdown"
      :order="order"
      v-if="markdown !== ''"
    ></MarkdownRender>
    <slot></slot>
  </article>
</template>
