<template>
  <div>
    <v-skeleton-loader
      v-if="loading"
      type="list-item"
      loading
    ></v-skeleton-loader>

    <v-select
      v-if="!loading"
      :label="$t(label_field)"
      :value="data"
      :items="items"
      item-text="label"
      item-value="value"
      @change="update"
      :rules="rules"
      :disabled="readOnly"
    ></v-select>
  </div>
</template>

<script lang="ts">
  import {computed, defineComponent, ref, toRef, useContext, useFetch} from '@nuxtjs/composition-api'
  import {$enumDataProvider} from "~/services/dataProvider/enumDataProvider";
  import {AnyJson} from "~/types/types";
  import {useRepositoryHelper} from "~/use/store/useRepository";
  import {Repository} from "@vuex-orm/core";
  import {Model} from "~/models/Model";

  export default defineComponent({
    props: {
      repository: {
        type: Object as () => Repository<Model>,
        required: true
      },
      entry:{
        type: Object,
        required: true
      },
      field: {
        type: String,
        required: true
      },
      label: {
        type: String,
        required: false
      },
      enumType: {
        type: String,
        required: true
      },
      rules: {
        type: Array,
        required: false
      }
    },
    setup(props){
      const {label, field, repository, enumType } = props
      const entry = toRef(props, 'entry')

      const {$rest, app: {i18n}} = useContext()
      const label_field = label ?? field;

      const data = computed(() => entry.value[field])
      const update = (newValue:string) => useRepositoryHelper.updateStoreFromField(repository, entry.value, newValue, field)
      const readOnly = computed(() => useRepositoryHelper.getReadOnly(repository))

      const loading = ref(true)
      const items: AnyJson = ref([])
      const {fetch, fetchState} = useFetch(async () => {
        items.value = await $enumDataProvider($rest, i18n).get(enumType)
        loading.value = false
      })

      return {
        data,
        update,
        items,
        loading,
        label_field,
        readOnly
      }
    }
  })
</script>

<style scoped>
</style>
