<template>
  <div>
    <q-list highlight inset-separator sparse no-border>
      <q-item-label header>Quoi de neuf</q-item-label>
      <q-item mulitline
              link
              v-for="history in lastHistory"
              :key="history.timestamp"
              :to="`item/${history.ref}`"
      >
        <q-item-section avatar>
          <q-icon :name="history.image ? 'image' : 'chat'"></q-icon>
        </q-item-section>
        <q-item-section>
          <q-item-label lines="3" label>{{ history.text }}</q-item-label>
          <q-item-label caption>
            <span class="text-secondary">{{history.user}}</span>
            , au sujet de <b>{{ history.item.name}}</b> #{{history.ref}}
          </q-item-label>
        </q-item-section>

        <q-item-section side top>
          <q-item-label caption>{{timeAgo(history.date || history.created)}}</q-item-label>
        </q-item-section>
      </q-item>
    </q-list>
  </div>

</template>

<script>
import { date } from 'quasar'

export default {
  name: 'ActivityFeed',
  data () {
    return { }
  },
  computed: {
    stock () {
      return this.$store.state.core.firebase.stock || []
    },
    history () {
      return this.$store.state.core.firebase.history || []
    },
    username () { return this.$store.state.core.username },
    lastHistory () {
      let newHistory = JSON.parse(JSON.stringify(this.history)).slice(-15)
      for (let history of newHistory) {
        history.item = this.getStock(history.ref)
      }
      return newHistory.reverse()
    }
  },
  methods: {
    dateFormat (timestamp, format = 'DD/MM/YY - HH:ss') {
      return date.formatDate(timestamp, format)
    },
    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, 'days')
        return `il y a ${daysDiff} jour(s)`
      }
    },
    getStock (ref) {
      return this.stock.find(item => {
        return (item) ? item.ref === ref : false
      }) || []
    }
  }
}
</script>

<style>
</style>
