<template>
  <div>
    <b-autocomplete ref="autocomplete"
                    :name="name"
                    v-show="!selected"
                    v-model="autocompleteValue"
                    :data="data"
                    @typing="getAsyncData"
                    @select="selectionMade"
                    keep-first>
      <template slot-scope="props">
        {{ props.option.label }}
      </template>
    </b-autocomplete>

    <b-button v-if="selected"
              style="width: 100%; justify-content: left;"
              @click="clearSelection()">
      {{ selected.label }}
    </b-button>
  </div>
</template>

<script>
export default {
    name: 'ByjoveAutocomplete',
    props: {
        name: String,
        serviceUrl: String,
        value: String,
        initialLabel: String,
    },
    data() {
        let selected = null
        if (this.value) {
            selected = {
                value: this.value,
                label: this.initialLabel,
            }
        }
        return {
            data: [],
            selected: selected,
            isFetching: false,
            autocompleteValue: this.value,
        }
    },
    methods: {

        clearSelection() {
            this.selected = null
            this.$emit('input', null)
            this.autocompleteValue = null
            this.$nextTick(function() {
                this.$refs.autocomplete.focus()
            })
        },

        selectionMade(option) {
            this.selected = option
            this.$emit('input', option ? option.value : null)
        },

        // TODO: buefy example uses `debounce()` here and perhaps we should too?
        // https://buefy.org/documentation/autocomplete
        getAsyncData: function (entry) {
            if (entry.length < 3) {
                this.data = []
                return
            }

            this.isFetching = true
            this.$http.get(this.serviceUrl, {params: {term: entry}}).then((response) => {
                this.data = response.data
            }).catch((error) => {
                this.data = []
                throw error
            }).finally(() => {
                this.isFetching = false
            })
        },
    },

}
</script>
