﻿<template>

  <v-infinite-scroll :items="messages"
                     :onLoad="load"
                     mode="manual"
                     class="bg-gray-300 rounded-md justify-items-center">

    <template v-for="(message, index) in messages" :key="index">
      <Message
          :message="message"
          class="m-2 p-2 rounded-md bg-gray-100"
      >
      </Message>
    </template>

    <template v-slot:load-more="{ props }">
      <v-btn
          size="small"
          variant="plain"
          v-bind="props"
      >Voir plus de commentaires
      </v-btn>
    </template>

    <template v-slot:empty>
      Il n'y a pas plus de commentaires
    </template>

    <template v-slot:error>
      <v-alert type="error">{{ errorMessage }}</v-alert>
    </template>

  </v-infinite-scroll>

</template>

<script setup>

import Message from "@/views/messages/Message.vue";

import {useClient} from '@/plugins/api.js';
import {defineProps, onBeforeMount, ref} from 'vue';

const props = defineProps({
  subjectId: {
    type: String,
    required: true
  }
});

const errorMessage = ref()
let last_id = null
const client = useClient();
const messages = ref([]);

onBeforeMount(async () => {
  if (props.subjectId == null) return
  await load({
    page_size: 2,
    done: function (status) {
      console.log(`Loading status: ${status}`)
    }
  })
})

async function load({done, page_size}) {
  if (props.subjectId == null) return
  if (page_size === undefined) page_size = 10

  try {
    let uri = `/api/messages/${props.subjectId}?page_size=${page_size}`
    if (last_id !== null) uri = uri + `&last_id=${last_id}`

    console.log(`Fetching messages at: ${uri}`)
    const response = await client.get(uri)

    if (response.status >= 200 && response.status < 300) {

      const messageCount = response.data.length

      if (messageCount > 0) {
        messages.value.push(...response.data)
        const [last_content] = response.data.slice(-1)
        last_id = last_content.id
      }

      if (messageCount < page_size)
        done('empty')
      else
        done('ok')
    }
  } catch (error) {
    console.error("Failed to fetch posts", error);
    errorMessage.value = error
    done('error')
  }
}

</script>