<template>
  <div class='admin_users' ref='scrollElement'>
    <h1 class='admin_users__header'>Users</h1>
    <div class='category_widget__box'>
      <div class='admin_users__filters'>
        <b-input
          :large='false'
          v-model='search'
          placeholder="Search Kaverti users"
          icon="search"
        ></b-input>
      </div>
    </div>
    <scroll-load
      class='category_widget__box'
      @loadNext='fetchData'
      :loading='loading'
      query-selector='.admin_users'
      :padding-bottom='100'
    >
      <div class="card" v-for='user in users' :key='"user-row" + user.username' v-show="user && !user.hidden">
        <div class="card-content">
          <div class="media">
            <div class="media-left">
              <figure class="image is-48x48">
                <avatar-icon :user="user"/>
              </figure>
            </div>
            <div class="media-content">
              <router-link :to='"/user/" + user.username'><p class="title is-4">{{user.username}}</p></router-link>
              <b-tooltip v-if='user && user.system' class="is-success" label="This user is a system user operated by administrators that mainly run API operations.">
                <b-tag rounded class="is-success">SYSTEM&nbsp;<i class="fas fa-info-circle"></i></b-tag>
              </b-tooltip>
              &nbsp;
              <b-tooltip v-if='user && user.bot' class="is-info" label="This user is a bot account that can run automated API operations.">
                <b-tag rounded class="is-info">BOT&nbsp;<i class="fas fa-info-circle"></i></b-tag>
              </b-tooltip>
              &nbsp;
              <b-tooltip v-if='user && user.admin' class="is-danger" label="User is an official Kaverti administrator.">
                <b-tag class="is-danger" rounded>ADMIN&nbsp;<i class="fas fa-info-circle"></i></b-tag>
              </b-tooltip>
              &nbsp;
              <b-tooltip v-if='user && user.hidden' class="is-info" label="User is not discoverable in the user list.">
                <b-tag rounded>HIDDEN&nbsp;<i class="fas fa-info-circle"></i></b-tag>
              </b-tooltip>
              &nbsp;
              <b-tooltip v-if='user && user.booster' class="is-primary" label="User is boosting the Kaverti Discord server.">
                <b-tag class="is-primary" rounded>BOOSTER&nbsp;<i class="fas fa-info-circle"></i></b-tag>
              </b-tooltip>
            </div>
          </div>

          <div class="content">
            {{user.description}} <br/>
            {{user.createdAt | formatDate}}
          </div>
        </div>
      </div>
      <transition name='fade' mode='out-in'>
        <loading-message key='loading' v-if='loading'></loading-message>
        <div class='overlay_message' v-if='!loading && !users.length'>
          No users found
        </div>
      </transition>
    </scroll-load>
  </div>
</template>

<script>
  import LoadingMessage from '../LoadingMessage';
  import ScrollLoad from '../ScrollLoad';
  import AvatarIcon from '../AvatarIcon';
  import throttle from 'lodash.throttle';
  import AjaxErrorHandler from '../../assets/js/errorHandler';

  export default {
    name: 'UserList',
    components: {
      LoadingMessage,
      ScrollLoad,
      AvatarIcon
    },
    data () {
      return {
        search: '',
        users: [],

        loading: true,
        offset: 0,
        limit: 15,

        roleOptions: [
          { name: 'Admins', value: 'admin' },
          { name: 'Users', value: 'user' }
        ],
        roleSelected: ['admin', 'user'],

        tableSort: {
          column: 'username',
          sort: 'desc'
        }
      }
    },
    methods: {
      recaptcha() {
        this.$recaptcha('login').then((token) => {
          console.log(token) // Will print the token
        })},
      fetchData () {
        if(this.offset === null) return;

        let url = `/api/v1/user?
					sort=${this.tableSort.column}
					&order=${this.tableSort.sort}
					&offset=${this.offset}
				`;
        if(this.roleSelected.length === 1) {
          url += '&role=' + this.roleSelected[0];
        }
        if(this.search.length) {
          url += '&search=' + encodeURIComponent(this.search.trim());
        }

        this.loading = true;
        this.axios
          .get(url)
          .then(res => {
            this.users.push(...res.data);
            this.loading = /*loading =*/ false;

            //If returned data is less than the limit
            //then there must be no more pages to paginate
            if(res.data.length < this.limit) {
              this.offset = null;
            } else {
              this.offset+= this.limit;
            }
          })
          .catch(e => {
            AjaxErrorHandler(this.$store)(e);
            this.loading = /*loading =*/ false;
          });
      },
      resetFetchData () {
        this.offset = 0;
        this.users = [];

        this.fetchData();
      }
    },
    getNewerUsers () {
      this.loadingNewer = true

      this.axios
        .get('/api/v1/users' + '?limit=' + this.newUsers)
        .then(res => {
          this.loadingNewer = false
          this.newUsers = 0

          this.threads.unshift(...res.data.Threads)
        })
        .catch((e) => {
          this.loadingNewer = false
          AjaxErrorHandler(this.$store)(e)
        })
    },
    mounted () {
      this.fetchData();
    },
    watch: {
      tableSort: 'resetFetchData',
      roleSelected: 'resetFetchData',
      search: throttle(function () {
        this.resetFetchData();
      }, 200)
    }
  }
</script>

<style lang='scss' scoped>
  @import '../../assets/scss/variables.scss';

  .admin_users {
    padding: 1rem 2rem;

    @at-root #{&}__header {
      margin: 0.5rem 0 1rem 0;
    }

    @at-root #{&}__filters {
      margin-bottom: 0.5rem;

      .select_filter {
        margin-right: 0.5rem;
      }
    }

    table {
      border-collapse: collapse;
      width: 100%;

      th {
        border-bottom: 0.125rem solid $color__gray--darker;
        padding: 0.5rem 0.75rem;
        text-align: left;
      }

      tr {
        cursor: default;

        &:first-child {
          background-color: #fff;
        }
        &:nth-child(odd) {
          background-color: lighten($color__gray--primary, 20%);
        }
        &:nth-child(even) {
          background-color: $color__gray--primary;
        }
      }

      td {
        padding: 0.75rem;
      }
    }
    @at-root #{&}__user_column {
      display: flex;
      align-items: center;

      a {
        margin: 0 0.25rem;
      }
    }

    .overlay_message {
      padding-top: 2rem;
      padding-bottom: 1rem;
    }
  }
</style>
