<template>
  <div class="basic-search">
    <div>
      <label v-if="caption">{{caption}}</label>
      <input type="text" class="form-control" v-model="searchQuery" :placeholder="placeholder">
    </div>
    <div class="position-relative" v-if="searchResult.length">
      <div class="position-absolute basic-search-drop">
        <div class="list-group">
          <a v-for="(item, index) in searchResult" :key="`search-result_${index}`" class="list-group-item list-group-item-action" @click="handleAnswer(item)" href="javascript:;">{{ Object.values(item)[0] }}</a>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    caption: { type: String },
    placeholder: { type: String, default: 'Type your keyword' },
    dataset: { type: Object, default: () => {} },
    value: { type: String, default: '' },
    clear: { type: Boolean, default: false }
  },
  data() {
    return {
      searchQuery: '',
      searchResult: [],
      answered: false
    }
  },
  methods: {
    search() {
      const vm = this
      vm.searchResult = []
      if(!vm.searchQuery) return;
      if(vm.answered) {
        vm.answered = false
        return;
      }
      const keys = Object.keys(vm.dataset)
      keys.forEach((key) => {
        if(typeof vm.dataset[key] === 'string') {
          let normalizedData = vm.dataset[key].normalize('NFKD').replace(/[^\w\s.,-_\/]/g, '').toLowerCase().trim()
          let normalizedQuery = vm.searchQuery.normalize('NFKD').replace(/[^\w\s.,-_\/]/g, '').toLowerCase().trim()
          if(normalizedData.search(normalizedQuery) !== -1) vm.searchResult.push({[key]: vm.dataset[key]})
        }
      })
    },
    handleAnswer(item) {
      const vm = this
      vm.answered = true
      vm.searchQuery = Object.keys(item)
      vm.$emit('input', vm.searchQuery[0])
      vm.hideResults()
      vm.search()
      vm.answered = true
    },
    hideResults() {
      const vm = this
      vm.searchResult = []
    },
  },
  mounted() {
    const vm = this
    vm.searchQuery = JSON.parse(JSON.stringify(vm.value))
    if(vm.value) {
      vm.answered = true
    } else {
      vm.answered = false
    }
  },
  watch: {
    searchQuery() {
      const vm = this
      if(!vm.searchQuery) {
        vm.answered = false
        vm.clear = false
        vm.$emit('input', null)
      }
      clearTimeout(vm.timeout)
      vm.timeout = setTimeout(() => vm.search(), 500)
    },
    clear() {
      const vm = this
      if(vm.clear) {
        vm.searchQuery = ''
        vm.$emit('clear', false)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.basic-search-drop {
  z-index: 4000;
  max-height: 15rem;
  overflow-x: hidden;
  overflow-y: auto;
}
</style>
