<template>
  <v-card flat>
    <v-card-text>
      <v-autocomplete
        v-model="selectedModels"
        :items="items"
        :loading="isLoading"
        :search-input.sync="search"
        item-text="name"
        item-value="name"
        label="Select models by name"
        :no-data-text="noDataText"
        multiple
        chips
        small-chips
        deletable-chips
        dense
        outlined>

        <template v-slot:item="data">
          <v-list-item-content>
            <v-list-item-title v-text="data.item.name"/>
            <v-list-item-subtitle>{{ data.item.total }} {{ data.item.total | pluralize('material') }}</v-list-item-subtitle>
          </v-list-item-content>
        </template>

      </v-autocomplete>
    </v-card-text>
  </v-card>
</template>

<script>
export default {
  props: {
    value: {
      type: Array,
      required: true,
    },
  },
  data: () => ({
    entries: [],
    isLoading: false,
    search: null,
  }),
  computed: {
    noDataText() {
      if (this.items.length > 0) {
        return 'No models found for: ' + this.search
      } else {
        return 'Start typing to search...'
      }
    },
    selectedModels: {
      get() {
        return this.value
      },
      set(value) {
        this.$emit('input', value)
      }
    },
    items() {
      return this.entries
      /* return this.entries.map(entry => {
       *   const Description = entry.Description.length > this.descriptionLimit
       *     ? entry.Description.slice(0, this.descriptionLimit) + '...'
       *     : entry.Description

       *   return Object.assign({}, entry, { Description })
      })
       */
    },
  },
  watch: {
    search(val) {
      if (this.items.length > 0) return
      if (this.isLoading) return
      this.isLoading = true

      fetch('/api/v1/products/models')
        .then(res => res.json())
        .then(res => {
          this.entries = res
        })
        .catch(err => {
          // TODO
          console.log(err)
        })
        .finally(() => (this.isLoading = false))
    },
  },
}
</script>
