<template>

  <v-autocomplete
    ref="tagSearchInput"
    :value="value"
    :rules="rules"
    :items="items"
    :loading="isLoading"
    :search-input.sync="tagQuery"
    :label="label"
    :hint="hint"
    chips
    deletable-chips
    hide-selected
    hide-no-data
    no-filter
    return-object
    item-text="name"
    item-value="name"
    multiple
    @input="onSelect">

    <template
      slot="selection"
      slot-scope="{ item, selected }">

      <v-chip
        :selected="selected"
        class="chip--select-multi"
        close
        @input="remove(item)">
        {{ item.name | truncate }}
      </v-chip>

    </template>

    <template
      slot="item"
      slot-scope="{ item, tile }">
      <v-list-tile-content>
        <v-list-tile-title v-text="item.name"/>
      </v-list-tile-content>
    </template>

  </v-autocomplete>
</template>

<script>
import { fetchListRecords } from '../../utils/api'

export default {
  name: 'tagSearchInput',
  props: {
    value: {
      type: Array,
      default: () => []
    },
    rules: Array,
    label: String,
    hint: String
  },
  data () {
    return {
      isLoading: false,
      tagQuery: '',
      tags: []
    }
  },
  computed: {
    items () {
      if (this.value && !this.$contains(this.tags, this.value, 'name')) {
        return [...this.value, ...this.tags]
      } else {
        return this.tags
      }
    }
  },
  watch: {
    tagQuery (value) {
      this.searchTags(value)
    }
  },
  methods: {
    async searchTags (value) {
      if (value) {
        this.isLoading = true
        const response = await fetchListRecords('tags', {
          search: value,
          limit: 5
        })
        let tags = response.results
        if (!tags.length) {
          tags = [{
            header: 'Add new tag:'
          }, {
            name: value
          }]
        }
        this.tags = tags
        this.isLoading = false
      }
    },
    onSelect (value) {
      this.$emit('input', value)
    },
    remove (item) {
      let value = this.$remove(this.value, item, 'name')
      this.$emit('input', value)
    }
  }
}
</script>

<style lang="scss" scoped>
.v-autocomplete {
  margin-bottom:  10px;
}
</style>
