<template>
  <div class="vn-pp row justify-center">
    <toolbar>
      <div class="row">
        <q-badge
          v-if="count != null"
          class="text-subtitle1 q-mr-sm"
          color="secondary">
          {{$t('nConnections', [count])}}
        </q-badge>
      </div>
    </toolbar>
    <q-drawer
      v-model="$state.rightDrawerOpen"
      side="right"
      elevated>
      <div class="q-pa-md">
        <q-select
          :label="$t('refreshRate')"
          v-model="rate"
          :options="rates"
          @input="setTimeout"
          emit-value>
          <template v-slot:prepend>
            <q-icon name="timer"/>
          </template>
        </q-select>
        <q-select
          :label="$t('orderBy')"
          v-model="order"
          :options="orderOptions"
          @input="refresh"
          emit-value>
          <template v-slot:prepend>
            <q-icon name="sort"/>
          </template>
        </q-select>
      </div>
    </q-drawer>
    <div>
      <div
        v-if="connections && !connections.length"
        class="text-subtitle1 text-center text-grey-7 q-pa-md">
        {{$t('noDataFound')}}
      </div>
      <q-infinite-scroll
        ref="scroll"
        @load="onLoad"
        scroll-taget="html"
        :offset="500">
        <q-card class="vn-w-md">
          <q-list bordered separator>
            <q-item
              v-for="conn in connections"
              :key="conn.id"
              :to="`/access-log/${conn.userVisit.user.id}`"
              :title="$t('accessLog')"
              clickable>
              <q-item-section>
                <q-item-label>
                  {{conn.userVisit.user.nickname}}
                </q-item-label>
                <q-item-label caption>
                  {{conn.lastUpdate | relTime}}
                </q-item-label>
                <q-item-label caption>
                  {{conn.userVisit.access.agent.platform}} -
                  {{conn.userVisit.access.agent.browser}}
                  {{conn.userVisit.access.agent.version}}
                </q-item-label>
              </q-item-section>
            </q-item>
          </q-list>
        </q-card>
        <template slot="loading">
          <div class="row justify-center q-my-md">
            <q-spinner color="primary" name="dots" size="40px" />
          </div>
        </template>
      </q-infinite-scroll>
    </div>
    <q-page-sticky position="bottom-right" :offset="[18, 18]">
      <q-btn
        fab
        icon="refresh"
        color="accent"
        @click="refresh"
        :title="$t('refresh')"
      />
    </q-page-sticky>
  </div>
</template>

<script>
import Page from 'components/Page'

export default {
  name: 'Connections',
  mixins: [Page],
  data () {
    return {
      connections: null,
      pageSize: 30,
      limit: 0,
      rate: 5,
      count: null,
      rates: [
        {
          label: this.$t('dontRefresh'),
          value: null
        }
      ],
      order: 'lastUpdate DESC',
      orderOptions: [
        {
          label: this.$t('lastAction'),
          value: 'lastUpdate DESC'
        }, {
          label: this.$t('sessionInit'),
          value: 'created DESC'
        }
      ]
    }
  },
  created () {
    this.$state.useRightDrawer = true
  },
  mounted () {
    let seconds = [1, 2, 5, 10, 30]
    for (let secs of seconds) {
      this.rates.push({
        label: this.$t('nSeconds', [secs]),
        value: secs
      })
    }
  },
  beforeDestroy () {
    this.clearTimeout()
  },
  methods: {
    onLoad (index, done) {
      this.limit = this.pageSize * index
      this.refresh()
        .then(() => {
          done(this.connections.length < this.limit)
        })
        .catch((err) => {
          done(true)
          throw err
        })
    },
    refresh () {
      this.clearTimeout()
      let where = { userVisitFk: { neq: null } }
      let filter = {
        fields: ['created', 'lastUpdate', 'userVisitFk'],
        order: this.order,
        limit: this.limit,
        where,
        include: {
          relation: 'userVisit',
          scope: {
            fields: ['accessFk', 'userFk'],
            include: [
              {
                relation: 'access',
                scope: {
                  fields: ['agentFk'],
                  include: {
                    relation: 'agent',
                    scope: {
                      fields: [
                        'platform',
                        'browser',
                        'version'
                      ]
                    }
                  }
                }
              }, {
                relation: 'user',
                scope: {
                  fields: ['id', 'nickname']
                }
              }
            ]
          }
        }
      }
      return this.$axios.get(`UserSessions`, { params: { filter } })
        .then(res => (this.connections = res.data))
        .then(() => this.$axios.get(`UserSessions/count`, { params: { where } }))
        .then(res => (this.count = res.data.count))
        .finally(() => this.setTimeout())
    },
    setTimeout () {
      this.clearTimeout()
      if (this.rate) {
        this.timeout = setTimeout(
          () => this.refresh(), this.rate * 1000)
      }
    },
    clearTimeout () {
      if (this.timeout) {
        clearTimeout(this.timeout)
        this.timeout = null
      }
    }
  }
}
</script>
