<template>
  <div class="autocomplete-container" :class="$vuetify.breakpoint.name">
    <v-combobox
        v-model="select"
        :loading="loading"
        :items="items"
        :search-input.sync="search"
        item-text="label"
        :menu-props="{maxHeight: $vuetify.breakpoint.name === 'xs' ? 190 : 500, transition: 'fade-transition', allowOverflow: true}"
        prepend-inner-icon="search"
        :append-icon="null"
        return-object
        rounded
        hide-no-data
        auto-select-first
        no-filter
        hide-details
        label="Søk..."
        solo
        full-width
        flat
        outlined
        placeholder="Søk her"
        ref="autocomplete"
        color="primary"
        :dense="$vuetify.breakpoint.smAndDown"
      >
      <template v-slot:item="data">
      <span class="search-hit">{{data.item.label}} </span> ({{data.item.lang ? data.item.lang : 'fritekstsøk'}})
      </template>
    </v-combobox>
  </div>
</template>

<script>
  import axios from "axios"
  import debounce from "debounce"

  export default {
    props: {
      endpoint: String,
    },
    data: function() {
      return {
        loading: false,
        items: [],
        search: null,
        select: null,
        suggesting: null,
        debounced: debounce(function(q, self) {
          self.loading = true
          return axios.get(self.endpoint + 'suggest?', { params: {q: q,
                                                                  dict: this.$parent.lang,
                                                                  n: 9}} )
                      .then(
                            function(response) {
                                  let currentSearch = self.$refs.autocomplete.searchInput
                                  if (currentSearch == q) {

                                    let hits = []
                                    response.data.forEach((item, i) => {
                                      let hit = {q: q, match: item[0], label: item[0]}
                                      hit.lang = item[1][1] ? "bm, nn" : {"bob": "bm", "nob": "nn"}[item[1][0]]
                                      hits.push(hit)

                                    });

                                    hits.push({q: currentSearch, label: currentSearch})
                                    self.items = hits
                                  }
                                
                                
                                
                                self.loading = false
                              })
        }, 100)
      }
    },
    watch: {
      search (val) {
        if (! val) {
          this.items = []
        } else {
          this.run_query(val)
        }
      },
      select(item) {
        this.items = []
        if (item) {
          if (typeof item === 'string') { // if blurred without selecting an option
             // TODO: sett timeout for å vente på siste forslag?
            item = {q: item, label: item}

          }
          if (item.q == this.$refs.autocomplete.searchInput) {
              this.$emit('submit', item)
              let self = this
              setTimeout(() => self.$refs.autocomplete.$refs.input.select(), 1)
          }
          
        }
      }
    },
    methods: {
      run_query(q) {
        this.items = []
        this.debounced(q, this)
      }
    },
  }
</script>


<style scoped>
  .search-hit {
    font-weight: bold;
    margin-right: 5px;
    color: var(--v-primary-base);
  }

  .autocomplete-container {
    padding-left: 10px;
    padding-right: 10px;
  }
</style>