<template>
  <q-layout v-if="!loading"> <!-- Be sure to play with the Layout demo on docs -->
    <q-header class="no-shadow text-center">
      <q-toolbar color="secondary" inverted>
        <q-btn
          flat
          size="18px"
          icon="o_menu"
          color="secondary"
          @click="leftDrawer = !leftDrawer"
        />
        <q-toolbar-title class="text-center">
          <div class="q-px-md" @click="$router.push('/dashboard')" style="display:inline-block;cursor:pointer">
            <img src="~assets/gyoza.svg" style="height:36px">
          </div>
        </q-toolbar-title>
        <q-btn flat class="no-pointer-events" color="secondary">{{username}}</q-btn>
        <q-btn
          flat
          size="18px"
          icon="o_logout"
          @click="unsetUser()"
          color="secondary"
        />
      </q-toolbar>
    </q-header>
    <q-drawer
      side="left"
      v-model="leftDrawer"
    >
        <q-list highlight
                no-border
                inset-separator
        >
          <q-item-label header>Catégories</q-item-label>
          <q-item v-for="category in categories"
                  :key="category.code"
                  :to="'/category/' + category.code"
          >
            <q-item-section>{{ category.name }}</q-item-section>
            <q-item-section side>
              <q-chip square
                      dense
                      color="secondary"
                      text-color="white"
              >{{ counters[category.name] }}</q-chip>
            </q-item-section>
            <q-item-section side>
              <q-btn round
                     flat
                     size="md"
                     icon="o_add"
                     :title="`Ajouter un(e) ${category.name}`"
                     @click.stop.prevent="addItem(category)"
              >
              </q-btn>
            </q-item-section>
          </q-item>
          <!--<q-item-separator />-->
          <!--<q-list-header>Previous chats</q-list-header>-->
          <!--<q-item>-->
            <!--<q-item-side avatar="statics/guy-avatar.png" />-->
            <!--<q-item-main label="Jack Doe" />-->
          <!--</q-item>-->

          <!--          PRINT STUFF-->
          <q-separator/>
          <q-item-label header>Utilitaires</q-item-label>
          <q-item :to="'/tasks'"
          >
            <q-item-section>Tâches</q-item-section>
            <q-item-section side>
              <q-icon name="o_task"></q-icon>
            </q-item-section>
          </q-item>
          <q-item :to="'/print-settings'"
                  disable
          >
            <q-item-section>Impression</q-item-section>
            <q-item-section side>
              <q-icon name="o_print"></q-icon>
            </q-item-section>
          </q-item>
        </q-list>
    </q-drawer>

    <q-page-container>
      <!-- This is where pages get injected -->
      <router-view />
    </q-page-container>

  </q-layout>
</template>

<script>
import { QSpinnerBars, date } from 'quasar'

export default {
  name: 'DefaultLayout',
  data () {
    return {
      leftDrawer: true,
      loading: false,
      dataRef: null
    }
  },
  computed: {
    categories () {
      return this.$store.state.core.firebase.categories
    },
    counters () {
      let stock = this.$store.state.core.firebase.stock
      let result = {}
      if (!this.categories || !stock) return result
      for (let cat of this.categories) {
        let catStock = stock.filter(item => { return item.type === cat.name })
        let lastRef = (catStock[catStock.length - 1] || {}).ref
        let ref = lastRef ? parseInt(lastRef.split('-')[1]) : 0
        result[cat.name] = ref
      }
      return result
    },
    username () {
      return this.$store.state.core.username
    }
  },
  created () {
    this.loading = true
    this.$q.loading.setDefaults({
      spinner: QSpinnerBars,
      message: 'OK, laisse moi juste le temps de charger...',
      messageColor: 'white',
      spinnerSize: 150, // in pixels
      spinnerColor: 'white',
      customClass: 'bg-secondary',
      delay: 0
    })
    this.$q.loading.show()
    this.loadAppData()
    // Realtime reactivity to DB changes
    // TODO: Fix this
    // this.dataRef = Firebase.database().ref()
    // this.dataRef.on('value', (snapshot) => {
    //   this.$store.dispatch('core/loadAppData')
    // })
  },
  mounted () {
    let username = this.$q.localStorage.getItem('username')
    console.log('user', username)
    if (!username) {
      this.$q.dialog({
        title: 'Hey salut !',
        message: 'Moi c\'est Gyōza. C\'est quoi ton pseudo ?',
        prompt: {
          model: '',
          type: 'text' // optional
        },
        cancel: false,
        preventClose: true,
        color: 'secondary'
      }).onOk(username => {
        this.$q.localStorage.set('username', username)
        this.$store.commit('core/setUsername', username)
        this.$q.notify({
          message: `Enchanté ${username} !`,
          color: 'green',
          avatar: '/gyoza.svg',
          timeout: 2000
        })
      })
    } else {
      this.$store.commit('core/setUsername', username)
    }
  },
  methods: {
    loadAppData () {
      this.$q.loading.show()
      return this.$store.dispatch('core/loadAppData').then(data => {
        console.log(data)
        this.$q.loading.hide()
        this.loading = false
      })
    },
    unsetUser () {
      this.$q.dialog({
        title: 'Une petite seconde...',
        message: 'Tu vas être déconnecté(e) là. C\'est vraiment ça que tu veux ?',
        color: 'primary',
        ok: 'Bah oui, FDP',
        cancel: 'Ah non en fait'
      })
        .onOk(() => {
          this.$q.localStorage.remove('username')
          this.$q.localStorage.remove('credentials')
          this.$router.push('/')
        })
    },
    async addItem (category) {
      this.$q.loading.show()
      // Get next short id
      let shortId = await this.$store.dispatch('core/getNextShortId')
      let newItem = {
        available: true,
        comment: '',
        name: '',
        owner: 'HFS',
        ref: null,
        state: null,
        type: category.name,
        system: null,
        short_id: shortId
      }
      newItem.ref = `${category.code}-${String(this.counters[category.name] + 1).padStart(4, '0')}`
      await this.$store.dispatch('core/addToCollection', {
        collection: 'stock',
        data: newItem
      })
      // Insert history record
      await this.$store.dispatch('core/addToCollection', {
        collection: 'history',
        data: {
          ref: newItem.ref,
          text: 'Entrée en stock',
          user: this.$store.state.core.username,
          timestamp: Date.now()
        }
      })
      await this.loadAppData()

      // Process to new item
      this.$q.loading.hide()
      this.$q.dialog({
        title: `Item "${category.name}" créé`,
        message: 'Tu veux aller éditer les détails de cet item ?',
        color: 'primary',
        ok: 'Oui, STP',
        cancel: 'Osef'
      })
        .onOk(() => {
          this.$router.push(`/item/${newItem.ref}`)
        })
    }
  }
}
</script>

<style>
</style>
