<!--
Espace permettant de récupérer un item via une uri et de gérer son affichage via un slot
-->

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

<script lang="ts">
import { defineComponent, useFetch, useContext, ComputedRef, computed } from '@nuxtjs/composition-api'
import {QUERY_TYPE} from "~/types/enums";
import { Query } from '@vuex-orm/core'
import { Item } from '@vuex-orm/core/dist/src/data/Data'
import ModelsUtils from "~/services/utils/modelsUtils";
import {queryHelper} from "~/services/store/query";

export default defineComponent({
  props: {
    uri: {
      type: String,
      required: false,
      default: null
    },
    model: {
      type: Function,
      required: true
    },
    query: {
      type: Object as () => Query,
      required: true
    },
    loaderType: {
      type: String,
      required: false,
      default: 'text'
    }
  },
  setup (props) {
    const { $dataProvider } = useContext()
    const getIdFromUri = (uri: string) => {
      return ModelsUtils.extractIdFromUri(uri)
    }
    const id = getIdFromUri(props.uri)

    useFetch(async () => {
      await $dataProvider.invoke({
        type: QUERY_TYPE.MODEL,
        model: props.model,
        id: id
      })
    })
    const item: ComputedRef<Item|null> = computed(() => {
      if(id)
        return queryHelper.getItem(props.query, id)
      else return null
    })

    return {
      item
    }
  }
})
</script>
