<!--
Liste déroulante avec autocompletion (les données sont issues
d'une api)

@see https://vuetifyjs.com/en/components/autocompletes/#usage
-->
<template>
  <main>
    <UiInputAutocomplete
      :field="field"
      :label="label"
      :data="data"
      :items="items"
      :isLoading="isLoading"
      :item-text="itemText"
      :slotText="slotText"
      :item-value="itemValue"
      prependIcon="mdi-magnify"
      :return-object="returnObject"
      @research="search"
      :no-filter="noFilter"
      @update="$emit('update', $event, field)"
    />
  </main>
</template>

<script lang="ts">
import {defineComponent, ref, Ref, watch, onUnmounted, toRefs} from '@nuxtjs/composition-api'

export default defineComponent({
  props: {
    label: {
      type: String,
      required: false,
      default: null
    },
    field: {
      type: String,
      required: false,
      default: null
    },
    searchFunction: {
      type: Function,
      required: true
    },
    data: {
      type: [String, Number, Object, Array],
      required: false,
      default: null
    },
    readonly: {
      type: Boolean,
      required: false
    },
    itemValue: {
      type: String,
      default: 'id'
    },
    itemText: {
      type: Array,
      required: true
    },
    slotText: {
      type: Array,
      required: false
    },
    returnObject: {
      type: Boolean,
      default: false
    },
    noFilter: {
      type: Boolean,
      default: false
    }
  },
  setup(props) {
    const {data} = toRefs(props)
    const items:Ref<Array<any>> = ref([data.value])
    const isLoading = ref(false)

    const search = async (research:string) => {
      isLoading.value = true

      const func: Function = props.searchFunction
      items.value = await func(research, props.field)

      isLoading.value = false
    }

    const unwatch = watch(data,(d) => {
      items.value = [d]
    })

    onUnmounted(() => {
      unwatch()
    })

    return {
      label_field: props.label ?? props.field,
      isLoading,
      items,
      search
    }
  }
})
</script>
