<template>
  <div v-if="user.authenticated">
    <h1 v-lang.logs.title></h1>

    <div class="fullscreen-loader-wrapper" v-if="loading">
      <div class="half-circle-spinner">
        <div class="circle circle-1"></div>
        <div class="circle circle-2"></div>
      </div>
    </div>

    <div v-if="!loading">

      <button @click="loadLogs()" class="ui teal labeled icon button" style="float: right;">
        <i class="refresh icon"></i>
        <span v-lang.general.refresh></span>
      </button>

      <form id="search">
        <div class="ui icon input">
          <input :placeholder="langGeneral.search" type="text" v-model="searchQuery" v-focus>
          <i class="search icon"></i>
        </div>
      </form>
      <paginate
        name="logs"
        :list="filteredData"
        :per="35"
        tag="div"
      >
        <grid
          :data="paginated('logs')"
          :columns="gridColumns"
        >
        </grid>
      </paginate>
      <div class="pagination-container">
        <paginate-links
          tag="div"
          for="logs"
          :hide-single-page="true"
          :classes="{
            'ul': ['ui', 'pagination', 'menu'],
            'li': 'item',
            'li a': 'pagination-link'
          }"
        >
        </paginate-links>
        <div v-if="$refs.paginator" v-lang.general.searchResultCount="$refs.paginator.pageItemsCount"></div>
      </div>
    </div>
  </div>
</template>

<script>
  import auth from '../auth'
  import {HTTP} from '../http-common'

  export default {
    name: 'Logs',
    data () {
      return {
        user: auth.user,
        logs: [],
        searchQuery: '',
        gridColumns: [],
        loading: false,
        paginate: ['logs'],
        allStatus: [],
        showModal: false,
        logActions: []
      }
    },
    created () {
      this.loadLogs()

      // Grid
      this.gridColumns = [
        this.translate('logs').gridColumns.user,
        this.translate('logs').gridColumns.action,
        this.translate('logs').gridColumns.itemID,
        this.translate('logs').gridColumns.date
      ]

      // Build the list with all logactions
      this.logActions = this.translate('logs').logActions

      // Set the title
      document.title = this.translate('nav').logs
    },
    watch: {
      // call again the method if the route changes
      '$route': 'loadLogs'
    },
    computed: {
      filteredData: function () {
        var filterKey = this.searchQuery && this.searchQuery.toLowerCase()
        var data = this.logs
        if (filterKey) {
          data = data.filter(function (row) {
            return Object.keys(row).some(function (key) {
              if (row[key].content) {
                return String(row[key].content).toLowerCase().indexOf(filterKey) > -1
              } else {
                return String(row[key]).toLowerCase().indexOf(filterKey) > -1
              }
            })
          })
        }
        return data
      },
      langGeneral () {
        return this.translate('general')
      }
    },
    methods: {
      errorNotification (e) {
        // Build the notification text from error response
        let err = e.message
        if (e.response.data && e.response.data.message) {
          err += '<br/>' + e.response.data.message
        }

        // Fire a notification
        this.$notify({
          type: 'error',
          title: this.langGeneral.error,
          text: err
        })
      },
      loadLogs () {
        this.loading = true
        this.logs = []
        HTTP.get(`logs`, { headers: {'Authorization': 'Bearer ' + localStorage.getItem('token')} })
          .then(response => {
            let ls = response.data
            let i = 0

            // Loop throught the data we got from our API and prepare an array to display all authors
            for (const l in ls) {
              // Beautify the date
              let c = new Date(ls[l].time * 1000)
              let time = {
                date: ('0' + c.getDate()).slice(-2) + '.' + ('0' + (c.getMonth() + 1)).slice(-2) + '.' + c.getFullYear(),
                time: ('0' + c.getHours()).slice(-2) + ':' + ('0' + c.getMinutes()).slice(-2)
              }

              let logAction = ls[l].log

              this.logs[i] = {
                id: {content: ls[l].id, hide: true}, // Don't show the id
                user: ls[l].userID,
                log: this.logActions[logAction],
                item: {content: ls[l].itemID, link: '#'},
                time: time.date + ' ' + time.time
              }

              // Build the item link
              // Book
              if (logAction === 1 || logAction === 2 || logAction === 3) {
                this.logs[i].item.link = '/books/' + ls[l].itemID
              }

              // Author
              if (logAction === 4 || logAction === 5 || logAction === 6) {
                this.logs[i].item.link = '/authors/' + ls[l].itemID
              }

              // Publisher
              if (logAction === 7 || logAction === 8 || logAction === 9) {
                this.logs[i].item.link = '/publishers/' + ls[l].itemID
              }

              // Item
              if (logAction === 10 || logAction === 11 || logAction === 12) {
                this.logs[i].item.link = '/items/' + ls[l].itemID
              }

              // User
              if (logAction === 13 || logAction === 14 || logAction === 15 || logAction === 16) {
                this.logs[i].item.link = '/users/' + ls[l].itemID
              }

              // increment dat shit
              i++
            }
            this.loading = false
          })
          .catch(e => {
            this.loading = false
            this.errorNotification(e)
          })
      }
    }
  }
</script>

<style>
  a.pagination-link{
    margin: -5px -1.14286em -18px;
    display: block;
    position: absolute;
    cursor: pointer;
    padding: 0.928571em 1.14286em;
    color: rgba(0,0,0,.87);

    -webkit-transition: background-color 200ms; /* Safari */
    transition: background-color 200ms;
  }

  a.pagination-link:hover{
    background: rgba(0,0,0,.02);
  }

  .pagination{
    padding: 0;
  }

  .pagination-container{
    margin-top: 1rem;
    text-align: center;
  }

  #search{
    margin-bottom: 1rem;
  }
</style>
