<!--
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="remoteData ? remoteData : data"
      :items="items"
      :isLoading="isLoading"
      :item-text="itemText"
      :slotText="slotText"
      :item-value="itemValue"
      :multiple="multiple"
      :chips="chips"
      prependIcon="mdi-magnify"
      :return-object="returnObject"
      @research="search"
      :no-filter="noFilter"
      @update="$emit('update', $event, field)"
    />
  </main>
</template>

<script setup lang="ts">

import {Ref, ref, toRefs} from "@vue/reactivity";
import UrlUtils from "~/services/utils/urlUtils";
import {FetchOptions} from "ohmyfetch";
import {useFetch} from "#app";
import {watch} from "@vue/runtime-core";

const props = defineProps({
  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
  },
  remoteUri: {
    type: [Array],
    required: false,
    default: null
  },
  remoteUrl: {
    type: String,
    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
  },
  multiple: {
    type: Boolean,
    default: false
  },
  chips: {
    type: Boolean,
    default: false
  }
})

const { data } = toRefs(props)
const items = ref([])
const remoteData: Ref<Array<string> | null> = ref(null)
const isLoading = ref(false)


if (props.data) {
  items.value = props.multiple ? (data.value ?? []) : [data.value]

} else if (props.remoteUri) {

  const ids:Array<any> = []

  for(const uri of props.remoteUri){
    ids.push(UrlUtils.extractIdFromUri(uri as string))
  }

  const options: FetchOptions = { method: 'GET', query: {key: 'id', value: ids.join(',')} }

  useFetch(async () => {
    isLoading.value = true

    const r: any = await $fetch(props.remoteUrl, options)

    isLoading.value = false
    remoteData.value = r.data
    items.value = r.data
  })
}

const search = async (research:string) => {
  isLoading.value = true
  const func: Function = props.searchFunction
  items.value = items.value.concat(await func(research, props.field))
  isLoading.value = false
}

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

onUnmounted(() => {
  unwatch()
})
</script>
