<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[1] ? "bm, nn" : {"bob": "bm", "nob": "nn"}[data.item.lang[0]] : '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: self.$parent.lang,
                                                                  n: 9}} )
                      .then(
                            function(response) {
                                  if (self.$refs.autocomplete.searchInput == q & self.suggesting) {

                                    let hits = []
                                    response.data.forEach((item, i) => {
                                      let hit = {q: q, match: item[0], label: item[0], articles: []}
                                      hit.lang = item[1]
                                      hits.push(hit)

                                    });
                                    // whitespace necessary because duplicates aren't allowed in the dropdown
                                    hits.push({q: q, label: q + ' '}) 
                                    self.items = hits
                                  }

                                self.loading = false                          
                              })
        }, 100)
      }
    },
    watch: {
      search (val) {
        if (! val) {
          this.items = []
        } else {
          this.run_query(val)
        }
      },
      select(item) {
        if (item) {
          if (typeof item != 'string') {
            let self = this
            if (item.articles) {
            axios.get(self.endpoint + 'articles?', {params: {lord: item.match,
                                                             dict: self.$parent.lang}})
              .then(
                function(response) {
                    ['bob', 'nob'].forEach((dict_tag) => {
                      response.data[dict_tag].forEach((article_id) => {
                        let article = {}
                        article.article_id = article_id
                        article.dictionary = dict_tag
                        article.match = item.match
                        item.articles.push(article)
                        })
                      })
                    }
                  )
              }
              this.items = []
              this.suggesting = false

              self.$emit('submit', item)

              setTimeout(() => {
                self.$refs.autocomplete.$refs.input.select()
                this.items = []
                this.suggesting = false
                }, 1)
            
          }
          // If blurred
          else {
            this.items = []
          }
        }
      }
    },
    methods: {
      run_query(q) {
        this.suggesting = true
        // Put full text search in the list while processing suggestions
        if (this.items[0]) {
          if (this.items[0].lang) {
          this.items.unshift({q: q, label: q})
        }
          else {
            this.items[0] = {q: q, label: q}
          }
        }
        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>