<!-- ? -->

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

<script lang="ts">
import { defineComponent, ref, computed, useContext, useFetch, toRefs, onUnmounted, 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
    }
  },
  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))
    // onUnmounted( useRepositoryHelper.cleanRepository(repository.value) )

    return {
      items
    }
  }
})
</script>
