<template>
  <base-search-box
    ref="child"
    v-bind="$attrs"
    @autocomplete-open="autocompleteOpen"
    @autocomplete-close="autocompleteClose"
    @change-autocomplete-view="changeAutocompleteView"
    @change="change"
  >
    <template
      #list-item="{
        hit,
        index,
        primaryKey,
        config,
        isHidden,
        onItemClick
      }"
    >
      <autocomplete-item
        :inner="hit.inner"
        :item="hit.item"
        :score="hit.score"
        :index="index"
        :primary-key="primaryKey"
        :template="config.listViewTemplate"
        :hidden="isHidden(hit)"
        @item-click="onItemClick"
      />
    </template>
    <template
      #grid-item="{
        hit,
        index,
        primaryKey,
        config,
        isHidden,
        onItemClick
      }"
    >
      <autocomplete-item
        :inner="hit.inner"
        :item="hit.item"
        :score="hit.score"
        :index="index"
        :primary-key="primaryKey"
        :template="config.gridViewTemplate"
        :hidden="isHidden(hit)"
        @item-click="onItemClick"
      />
    </template>
  </base-search-box>
</template>

<script>
import BaseSearchBox from './BaseSearchBox.vue'
import AutocompleteItem from './AutocompleteItem'

export default {
  name: 'MzSearchBox',
  components: {
    BaseSearchBox,
    AutocompleteItem
  },
  inheritAttrs: false,
  methods: {
    clearKeyword() {
      if (!this.$refs.child) {
        return
      }
      this.$refs.child.clearKeyword()
    },
    setupPopper() {
      if (!this.$refs.child) {
        return
      }
      this.$refs.child.setupPopper()
    },
    autocompleteOpen() {
      if (this.$bus) this.$bus.emit('autocomplete-open')
    },
    autocompleteClose() {
      if (this.$bus) this.$bus.emit('autocomplete-close')
    },
    changeAutocompleteView() {
      if (this.$bus) this.$bus.emit('change-autocomplete-vue')
    },
    change(value) {
      if (!this.$refs.child) {
        return
      }
      this.$emit('change', { value, input: this.$refs.child.input })
    }
  }
}
</script>
