<!-- Permet de requêter une subResource et de donner son contenu à un slot -->

<template>
  <main>
    <v-skeleton-loader
      v-if="fetchState.pending"
      :type="loaderType"
    />
    <div v-else>
      <slot name="list.item" v-bind="{items}" />

      <v-btn v-if="newLink" class="ot_white--text ot_green float-right">
        <NuxtLink :to="newLink" class="no-decoration">
          <v-icon>fa-plus-circle</v-icon>
          <span>{{$t('add')}}</span>
        </NuxtLink>
      </v-btn>
    </div>
    <slot />
  </main>
</template>

<script lang="ts">
import {
  defineComponent, computed, useContext, toRefs, ToRefs, ComputedRef
} from '@nuxtjs/composition-api'
import { Query } from '@vuex-orm/core'
import { Collection } from '@vuex-orm/core/dist/src/data/Data'
import { queryHelper } from '~/services/store/query'
import {useDataUtils} from "~/composables/data/useDataUtils";

export default defineComponent({
  props: {
    rootModel: {
      type: Function,
      required: false
    },
    rootId: {
      type: Number,
      required: false
    },
    model: {
      type: Function,
      required: true
    },
    query: {
      type: Object as () => Query,
      required: true
    },
    loaderType: {
      type: String,
      required: false,
      default: 'text'
    },
    newLink: {
      type: String,
      required: false
    }
  },
  setup (props) {
    const { rootModel, rootId, model, query }: ToRefs = toRefs(props)
    const { $dataProvider } = useContext()
    const { getCollection } = useDataUtils($dataProvider)
    const {fetchState} = getCollection(model.value, rootModel.value, rootId.value)
    const items: ComputedRef<Collection> = computed(() => queryHelper.getCollection(query.value))

    return {
      items,
      fetchState
    }
  }
})
</script>
