<!--
Liste déroulante dédiée à l'affichage d'objets Enum

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

<template>
  <main>
    <v-skeleton-loader
      v-if="$fetchState.pending"
      type="list-item"
      loading
    />

    <v-select
      v-else
      :label="$t(label_field)"
      :value="data"
      :items="items"
      item-text="label"
      item-value="value"
      :rules="rules"
      :disabled="readonly"
      :error="error || !!violation"
      :error-messages="errorMessage || violation ? $t(violation) : ''"
      @change="onChange($event)"
    />
  </main>
</template>

<script lang="ts">
import {defineComponent, ref, useContext, useFetch, Ref} from '@nuxtjs/composition-api'
import { EnumChoices } from '~/types/interfaces'
import { QUERY_TYPE } from '~/types/enums'
import {useError} from "~/composables/form/useError";

export default defineComponent({
  props: {
    enumType: {
      type: String,
      required: true
    },
    label: {
      type: String,
      required: false,
      default: null
    },
    field: {
      type: String,
      required: false,
      default: null
    },
    data: {
      type: String,
      required: false,
      default: null
    },
    readonly: {
      type: Boolean,
      required: false
    },
    rules: {
      type: Array,
      required: false,
      default: () => []
    },
    error: {
      type: Boolean,
      required: false
    },
    errorMessage: {
      type: String,
      required: false,
      default: null
    }
  },
  setup (props, {emit}) {
    const labelField = props.label ?? props.field

    const { enumType } = props
    const { $dataProvider, store } = useContext()
    const {violation, onChange} = useError(props.field, emit, store)

    const items: Ref<Array<EnumChoices>> = ref([])
    useFetch(async () => {
      items.value = await $dataProvider.invoke({
        type: QUERY_TYPE.ENUM,
        enumType
      })
    })


    return {
      items,
      label_field: labelField,
      violation,
      onChange
    }
  }
})
</script>

<style scoped>
</style>
