<!--
Tableau interactif

@see https://vuetifyjs.com/en/components/data-tables/
-->

<template>
  <v-col
    cols="12"
    sm="12"
  >
    <v-data-table
      :headers="headersWithItem"
      :items="entries"
      :server-items-length="totalEntries"
      :loading="$fetchState.pending"
      class="elevation-1"
    >
      <template v-for="header in headersWithItem" #[header.item]="props">
        <slot :name="header.item" v-bind="props">
          {{ props.item[header.value] }}
        </slot>
      </template>

      <template #item.actions="{ item }">
        <v-icon
          small
          class="mr-2"
          @click="editItem(item)"
        >
          mdi-pencil
        </v-icon>
        <v-icon
          small
          @click="deleteItem(item)"
        >
          mdi-delete
        </v-icon>
      </template>
    </v-data-table>
  </v-col>
</template>

<script lang="ts">
import { defineComponent, ref, useContext, useFetch, computed, toRefs, Ref } from '@nuxtjs/composition-api'
import { Query } from '@vuex-orm/core'
import { AnyJson } from '~/types/interfaces'
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
    },
    headers: {
      type: Array,
      required: true
    }
  },
  setup (props) {
    const { rootModel, rootId, model, headers, query } = toRefs(props)

    const headersWithItem = computed(() => {
      return headers.value.map((header:any) => {
        header.item = 'item.' + header.value
        return header
      })
    })

    const totalEntries:Ref<number> = ref(0)
    const entries:Ref<Array<AnyJson>> = ref(Array<AnyJson>())

    const { $dataProvider } = useContext()
    useFetch(async () => {
      await $dataProvider.invoke({
        type: QUERY_TYPE.MODEL,
        model: model.value,
        rootModel: rootModel.value,
        rootId: rootId.value
      })
      entries.value = queryHelper.getFlattenEntries(query.value)
      totalEntries.value = entries.value.length
    })

    const itemId:Ref<number> = ref(0)

    const editItem = (item: AnyJson) => {
      itemId.value = item.id
    }

    return {
      entries,
      totalEntries,
      headersWithItem,
      editItem,
      itemId
    }
  }
})
</script>
