<template>
  <div>
    <mz-search-box
      v-for="input of matches"
      :key="input.id"
      :input="input"
      :query-param="queryParam"
      :page-param="pageParam"
      :search-url="input.dataset.searchUrl || searchUrl"
      :placement="placement"
      :delay="parseInt(input.dataset.delay) || delay"
      :hide-autocomplete="input.dataset.hideAutocomplete === 'true'"
      :query-on-hover="queryOnHover"
      @change="onChange"
    ></mz-search-box>
  </div>
</template>

<script>
import MzSearchBox from './MzSearchBox'

export default {
  components: { 'mz-search-box': MzSearchBox },
  props: {
    selector: {
      type: String,
      required: false,
      default: 'input[name="q"]'
    },
    searchUrl: {
      type: String,
      required: true
    },
    queryParam: {
      type: String,
      required: false,
      default: 'q'
    },
    pageParam: {
      type: String,
      required: false,
      default: 'page'
    },
    placement: {
      type: String,
      required: false,
      default: undefined
    },
    delay: {
      type: Number,
      required: false,
      default: 0
    },
    queryOnHover: {
      type: Boolean,
      required: false,
      default: true
    }
  },
  data() {
    return {
      matches: []
    }
  },
  mounted() {
    this.$store.dispatch('search/setQueryParam', this.queryParam, {
      root: true
    })
    this.$store.dispatch('search/setPageParam', this.pageParam, {
      root: true
    })

    // load suggestions
    const self = this
    setTimeout(() => self.loadAutocomplete(), 200)
  },
  methods: {
    loadAutocomplete() {
      const itemList = document.querySelectorAll(this.selector)
      let inputs = []
      Array.from(itemList).forEach(function(item) {
        inputs.push(item)
      })
      this.matches = inputs
    },
    onChange({ input, value }) {
      input.value = value
    }
  }
}
</script>
