<template>
  <div>
    <q-input v-model="srcTxt"
              @update:model-value="updateSearchUrl"
              placeholder="Rechercher une référence ou un nom"
              autofocus
              clearable
    />
    <q-list highlight
            no-border
            v-if="searchResults.length > 0"
            class="q-mb-lg"
    >
      <q-item-label header>{{searchResults.length}} résultats de recherche pour "{{srcTxt}}"</q-item-label>
      <q-item multiline
              link
              :class="{'text-red': result.deleted}"
              v-for="result in searchResults"
              :key="result.ref"
              :to="`item/${result.ref}`"
      >
          <q-item-section label>{{ result.name }}</q-item-section>
          <q-item-section caption>
            <div>#{{ result.ref }}, dans <b class="text-secondary">{{ result.type }}</b></div>
          </q-item-section>
        <q-item-section side>{{`Etat: ${result.state}`}}</q-item-section>
      </q-item>
<!--      <q-item-separator />-->
    </q-list>

  </div>
</template>

<script>
import { date } from 'quasar'

export default {
  name: 'GlobalSearch',
  data () {
    return { srcTxt: null }
  },
  computed: {
    stock () {
      return this.$store.state.core.firebase.stock || []
    },
    searchResults () {
      if (!this.srcTxt || this.srcTxt.length < 3) return []
      return this.stock.filter(item => {
        return (item.ref + (item.name + '').toLowerCase()).search(this.srcTxt.toLowerCase()) !== -1
      }) || []
    }
  },
  created () {
    if (!this.srcTxt) this.srcTxt = this.$route.query.search || null
  },
  methods: {
    timeAgo (timestamp) {
      let date1 = new Date(timestamp)
      let date2 = Date.now()
      let hoursDiff = date.getDateDiff(date2, date1, 'hours')
      if (hoursDiff < 24) {
        return `il y a ${hoursDiff} heure(s)`
      } else {
        let daysDiff = date.getDateDiff(date2, date1)
        return `il y a ${daysDiff} jour(s)`
      }
    },
    updateSearchUrl () {
      this.$router.replace({ path: this.$router.path, query: { search: this.srcTxt } })
    }
  }
}
</script>

<style>
</style>
