﻿<template>

  <v-infinite-scroll :items="contents"
                     :onLoad="load"
                     class="bg-teal justify-items-center">

    <ContentCard v-for="content in contents"
                 :content="content"
                 class="my-2 p-4 bg-yellow-300 w-full"
    >
    </ContentCard>

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

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

  </v-infinite-scroll>

</template>

<script setup>

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

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

const client = useClient()
const contents = ref([])
const max_items = 10
const errorMessage = ref()
let last_id = null

async function load({done}) {
  try {
    let uri = `/api/contents/user/${props.creatorId}?max_items=${max_items}`
    if (last_id !== null) uri = uri + `&last_id=${last_id}`

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

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

      const contentCount = response.data.length

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

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

</script>