<style>
  .team-img {
    border-radius: 50%;
  }
  .vertical-alt {
    margin: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    -ms-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
  }
  .limit{
    margin-top: 0.5rem;
    word-break: break-all;
  }
</style>
<template>
  <main>
    <section class="hero is-info is-large" v-if="!$store.state.experimentsStore.teams">
      <div class="hero-body">
        <div class="container">
          <h2>
            Kaverti Teams
          </h2>
          <h1>
            Kaverti Teams are coming soon
          </h1>
          <h2 v-if="$store.state.developerMode">
            However, you're currently opted into Experiments, you can enable the Teams experiment in User Settings.
          </h2>
        </div>
      </div>
    </section>
    <b-modal :active="createTeamModal" v-model="createTeamModal">
      <div class="modal-card" style="width: auto">
        <template>
          <div class='route_container section route_container--settings'>
            <div class='column box'>
              <tab-view
                :tabs='["Create your own Team!"]'
                v-model="showTeamTab"
                padding='true'
                slot='main'
              >
                <template slot='Create your own Team!'>
                  <p style='margin-top: 0;'>
                    Creating a Kaverti team is easy!<br>
                    Just fill out the form here, you will be redirected to your team page automatically!<br>
                    Kaverti Teams cost 300 Koins to create.
                  </p>
                  <br/>

                  <form>
                    <fancy-input
                      ref='input'
                      v-model='tcreateProd.username'
                      :error='tcreateProd.errors.username'
                      placeholder='Username'
                      width='100%'
                    >
                    </fancy-input>
                    <fancy-input
                      v-model='tcreateProd.name'
                      :error='tcreateProd.errors.name'
                      placeholder='Name'
                      width='100%'
                      type="email"
                    >
                    </fancy-input>
                    By pressing the "Create Team" button, you agree to the <router-link to="/legal/tos" v-on:click.native="closeAccountModal">Kaverti Terms of Service</router-link> and have read the <router-link to="/legal/privacy" v-on:click.native="closeAccountModal">Privacy Policy</router-link>.
                    <div style='margin-top: 0.5rem;'>
                      <b-button
                        class='is-info'
                        style="width: 55%"
                        :loading='tcreateProd.loading'
                        @click='createTeam'
                        v-if='!$store.state.meta.RegistrationsDisabled'
                      >
                        Create Team
                      </b-button>
                      &nbsp;
                      <b-button style="float: right" class="is-danger-passive" @click='closeAccountModal'>
                        Cancel
                      </b-button>
                    </div>
                  </form>
                </template>
              </tab-view>
            </div>
          </div>
        </template>
      </div>
    </b-modal>
    <section v-if='$store.state.experimentsStore.teams' class="hero is-info">
      <div class="hero-body" style="padding: 1rem 1rem !important;">
        <div class="mobile-container">
          <div class="container">
            <p style="text-align: center;">Teams are currently in development, expect missing features.</p>
          </div>
        </div>
      </div>
    </section>
          <div class="section">
          <div class="">
            <div class="column" v-if="$store.state.username">
              <b-button @click="createTeamModal = true" class="is-primary">Create Team</b-button>
            </div>
            <scroll-load
              key='user-row'
              class='columns is-multiline'
              v-if='users.length'
              :loading='loading'
              @loadNext='fetchData'
            >
              <div class="column is-4" v-for='user in users' :key='"user-row" + user.username' v-show="user && !user.banned"><div class="card">
                <div class="card-content">
                  <router-link :to="'/t/' + user.username"><b-button style="float:right;">View</b-button></router-link>
                  <div class="media">
                    <div class="media-left">
                      <figure class="image is-64x64">
                        <img class="team-img" v-if="user.picture !== 'default' && user.approved" width="128px" height="128px" :src="user.picture">
                        <img class="team-img" v-if="user.picture === 'default' && $store.state.theme === 'light' && user.approved" width="128px" height="128px" src="https://cdn.kaverti.com/teams/unknown-light.png">
                        <img class="team-img" v-if="user.picture === 'default' && $store.state.theme === 'dark' && user.approved" width="128px" height="128px" src="https://cdn.kaverti.com/teams/unknown-dark.png">
                        <img class="team-img" v-if="$store.state.theme === 'light' && !user.approved" width="128px" height="128px" src="https://cdn.kaverti.com/teams/pending-light.png">
                        <img class="team-img" v-if="$store.state.theme === 'dark' && !user.approved" width="128px" height="128px" src="https://cdn.kaverti.com/teams/pending-dark.png">
                      </figure>
                    </div>
                    <div class="media-content">
                      <p class="title is-4">{{user.name}}</p>
                      <p class="subtitle is-6">@{{user.username}}</p>
                    </div>
                  </div>

                  <div class="content limit">
                    {{user.description | truncate(70)}}
                  </div>
                </div>
              </div>
              </div>
            </scroll-load>
          </div>
        </div>
        <p name='fade' mode='out-in'>
        <center><loading-message key='loading' v-if='loading'></loading-message></center>
        <center><div class='overlay_message' v-if='!loading && !users.length'>
          Something went wrong while loading the users, check your internet connection, or check the <a href="https://status.troplo.com">Service Status</a>
        </div></center></p>
  </main>
</template>
<script>
  import LoadingMessage from '../LoadingMessage';
  import ScrollLoad from '../ScrollLoad';
  import TabView from '../TabView'
  import FancyInput from '../FancyInput'
  import throttle from 'lodash.throttle';
  import AjaxErrorHandler from '../../assets/js/errorHandler';

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

        loading: true,
        offset: 0,
        limit: 15,
        showTeamTab: 0,
        createTeamModal: false,
        tcreateProd: {
          username: '',
          name: '',

          loading: false,

          errors: {
            username: '',
            name: ''
          }
        },

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

        tableSort: {
          column: 'username',
          sort: 'desc'
        }
      }
    },
    methods: {
      clearTeamErrors() {
        this.tcreateProd.errors.username = ''
        this.tcreateProd.errors.name = ''
      },
      closeAccountModal() {
        this.createTeamModal = false
      },
      createTeam() {
        let postParams = {
          username: this.tcreateProd.username,
          name: this.tcreateProd.name
        }
        this.tcreateProd.loading = true

        this.axios.post(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + `/` + `teams/create`, postParams).then(res => {
          this.tcreateProd.loading = false
          this.closeAccountModal(res)
        }).catch(e => {
          this.tcreateProd.loading = false
          AjaxErrorHandler(this.$store)(e);
        })
      },
      fetchData () {
        if(this.offset === null) return;

        let url = process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + `/` + `teams?
					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(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'teams' + '?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>
