<!-- 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, useFetch, 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 { QUERY_TYPE } from '~/types/enums'

export default defineComponent({
  props: {
    rootModel: {
      type: Function,
      required: true
    },
    rootId: {
      type: Number,
      required: true
    },
    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()
    useFetch(async () => {
      await $dataProvider.invoke({
        type: QUERY_TYPE.MODEL,
        model: model.value,
        rootModel: rootModel.value,
        rootId: rootId.value
      })
    })

    const items: ComputedRef<Collection> = computed(() => queryHelper.getCollection(query.value))

    return {
      items
    }
  }
})
</script>
