<template>
  <AdminTile class="admin-tile-games" title="Games">
    <table class="admin-tile-games__table">
      <tr>
        <th class="admin-tile-games__table-head">Game name</th>
        <th class="admin-tile-games__table-head">Lang</th>
        <th class="admin-tile-games__table-head">Status</th>
        <th class="admin-tile-games__table-head">#&nbsp;players</th>
        <th class="admin-tile-games__table-head">Gamemaster(s)</th>
      </tr>
      <tr
        class="admin-tile-games__game"
        @click="selectGame(id)"
        v-for="id in Object.keys(games || {})"
        :key="id"
      >
        <td>{{ games[id].name }}</td>
        <td>{{ games[id].lang }}</td>
        <td>{{ games[id].state }}</td>
        <td>{{ games[id].players.length }}</td>
        <td>{{ gamemasters[id] }}</td>
      </tr>
    </table>
  </AdminTile>
</template>

<script>
export default {
  props: ['games'],
  computed: {
    gamemasters() {
      const masters = {}
      for (const gameId of Object.keys(this.games || {})) {
        const game = this.games[gameId]
        for (const player of game.players) {
          if (player.role === 'gamemaster') {
            if (masters[gameId]) {
              masters[gameId] += ', '
              masters[gameId] += player.name
            } else {
              masters[gameId] = player.name
            }
          }
        }
      }
      return masters
    },
  },
  methods: {
    async selectGame(gameId) {
      const game = this.games[gameId]
      for (const player of game.players) {
        if (player.role === 'gamemaster') {
          await this.$axios.$get(`/api/cameo?code=${player.authcode}`)
          break
        }
      }
      this.$router.push('/gamemaster')
    },
  },
}
</script>

<style lang="scss">
.admin-tile-games {
  &__table {
    margin-left: -12px;
    border-collapse: separate;
    border-spacing: 12px 0;
  }
  &__table-head {
    text-align: left;
  }
  &__game {
    cursor: pointer;
    &:hover {
      color: #a0a0a0;
    }
  }
}
</style>
