<template>
  <AdminInfoTile title="Games">
    <table class="gameinfos-tile__table">
      <tr class="gameinfos-tile__row">
        <th class="gameinfos-tile__table-head">{{ $t('team-name')}}</th>
        <th class="gameinfos-tile__table-head">{{ $t('lang')}}</th>
        <th class="gameinfos-tile__table-head">{{ $t('state')}}</th>
        <th class="gameinfos-tile__table-head">{{ $t('num-players')}}</th>
        <th class="gameinfos-tile__table-head">{{ $t('gamemasters')}}</th>
      </tr>
      <tr class="gameinfos-tile__row" v-for="game in games" :key="game.id" @click="selectGame(game)">
        <td class="gameinfos-tile__cell">{{ game.name }}</td>
        <td class="gameinfos-tile__cell">{{ game.lang }}</td>
        <td class="gameinfos-tile__cell">{{ game.state }}</td>
        <td class="gameinfos-tile__cell">{{ game.players.length }}</td>
        <td class="gameinfos-tile__cell">{{ getGamemastersFromGame(game).join(', ') }}</td>
      </tr>
    </table>
  </AdminInfoTile>
</template>

<script setup lang="ts">
import { navigateTo } from "#app"
import { ref } from 'vue'
import useI18n from '@/composables/useI18n'
import useEngine from '@/composables/useEngine'
import type { GameInfo } from '@/composables/engine.d'

const { $t } = useI18n({
  'team-name': { en: 'Team name', de: 'Teamname' },
  lang: { en: 'Lang', de: 'Sprache' },
  state: { en: 'State', de: 'Status' },
  'num-players': { en: '# Players', de: '# Spieler' },
  gamemasters: { en: 'Gamemaster(s)', de: 'Gamemaster(s)' },
})

const { fetchGameInfos, cameo } = useEngine()

const games = ref(await fetchGameInfos())
const getGamemastersFromGame = (game: GameInfo) => game.players.filter((player) => player.role === 'gamemaster').map((player) => player.name)

const selectGame = async (game: GameInfo): Promise<void> => {
  for (const player of game.players) {
    if (player.role === 'gamemaster') {
      await cameo(player.authcode)
      break
    }
  }
  navigateTo('/gamemaster')
}
</script>

<style lang="scss">
.gameinfos-tile {
  &__table {
    margin: 0 0 16px 0;
    border-spacing: 0;
  }

  &__table-head {
    text-align: left;
    padding-right: 8px;
  }

  &__row {
    height: 24px;
    cursor: pointer;

    &:hover {
      background-color: #606060;
    }
  }

  &__cell {
    padding-right: 8px;
  }
}
</style>