<template>
  <AdminTile class="admin-tile-players" title="Players">
    <template v-slot:headerAction>
      <span
        v-if="!isReloading"
        class="admin-tile-players__action-reload"
        @click="reload"
      >
        ⟳
      </span>
    </template>
    <table class="admin-tile-players__table">
      <tr v-if="players.length">
        <th class="admin-tile-players__table-head">Name</th>
        <th class="admin-tile-players__table-head">#&nbsp;Quotes</th>
        <th class="admin-tile-players__table-head">Score</th>
        <th class="admin-tile-players__table-head">zuletzt eingeloggt</th>
      </tr>
      <tr
        class="admin-tile-players__player"
        @click="editPlayer(player)"
        v-for="player in players"
        :key="player.id"
      >
        <td>{{ player.name }}{{ player.role === 'gamemaster' ? ' 👑' : '' }}</td>
        <td>{{ player.numQuotes }}</td>
        <td>{{ player.score }}</td>
        <td>{{ getPlayerStatus(player) }}</td>
      </tr>
      <tr>
        <td colspan="4">
          <button class="admin-tile-players__add-player" @click="newPlayer()">+</button>
        </td>
      </tr>
    </table>
  </AdminTile>
</template>

<script>
export default {
  props: ['gameinfo', 'players'],
  data() {
    return {
      isReloading: false,
    }
  },
  methods: {
    editPlayer(player) {
      this.$emit('edit', player)
    },
    newPlayer() {
      this.$emit('edit', { id: null, name: '', score: 0, authcode: '' })
    },
    reload() {
      this.$emit('reload')
      this.isReloading = true
      setTimeout(() => { this.isReloading = false }, 500)
    },
    getPlayerStatus(player) {
      if (player.isPlaying && !player.isIdle) {
        return 'online'
      } else {
        if (player.lastLoggedIn) {
          return this.$formatter.datetime(player.lastLoggedIn)
        } else if (player.isPlaying) {
          return 'idle'
        }
      }
      return '-'
    },
  },
}
</script>

<style lang="scss">
.admin-tile-players {
  &__action-reload {
    float: right;
    cursor: pointer;

    &:hover {
      color: #c0c0c0;
    }
  }
  &__table {
    margin-left: -12px;
    border-collapse: separate;
    border-spacing: 12px 0;
  }
  &__table-head {
    text-align: left;
  }
  &__player {
    cursor: pointer;
    &:hover {
      color: #a0a0a0;
    }
  }
  &__add-player {
    padding: 0 3em;
    cursor: pointer;
  }
}
</style>
