<template>
  <b-container class="gamesListContainer">
    <b-row>
      <b-col cols="auto">
        <h1>
          Existing Games
        </h1>
        <div id="online-games">
          <div
            v-if="
              loadGamesStatus.status === $const('REQ_REQUESTED') ||
                loadGamesStatus.status === $const('REQ_IDLE') ||
                joinableGames.length === 0
            "
          >
            <h3>{{ loadGamesStatus.text }}</h3>
          </div>
          <div v-on-clickaway="unselect" v-else>
            <game-item
              v-for="(game, index) in joinableGames"
              :key="game.id"
              :game-element="game"
              @click.native="selectedIndex = index"
            ></game-item>
          </div>
        </div>

        <div id="online-room-buttons">
          <div>
            <button class="btn" @click="$emit('enter-game-creation')">
              New game
              <br />
              <b-icon icon="plus-circle"></b-icon>
            </button>
            <button
              class="btn"
              :disabled="resumeDisabled"
              @click="
                joinGame({
                  id: joinableGames[selectedIndex].id,
                  isNew: joinableGames[selectedIndex].player2 === ''
                })
              "
            >
              Join
              <br />
              <b-icon icon="controller"></b-icon>
            </button>
            <button class="btn btn_primary" @click="$emit('back')">
              Return
              <br />
              <b-icon icon="arrow-counterclockwise"></b-icon>
            </button>
          </div>
        </div>
      </b-col>
    </b-row>
  </b-container>
</template>

<script>
import GameItem from './components/GameItem';
import { mixin as clickaway } from 'vue-clickaway';
import { mapActions, mapGetters } from 'vuex';

export default {
  props: ['username'],
  data() {
    return {
      selectedIndex: -1,
      resumeDisabled: true
    };
  },
  components: {
    GameItem
  },
  watch: {
    selectedIndex() {
      if (this.selectedIndex >= 0) {
        this.resumeDisabled = false;
      } else {
        this.resumeDisabled = true;
      }
    }
  },
  methods: {
    ...mapActions({
      joinGame: 'menu/joinOnlineGame',
      fetchJoinableGames: 'menu/fetchJoinableGames'
    }),
    unselect() {
      this.selectedIndex = -1;
    }
  },
  computed: {
    ...mapGetters({
      joinableGames: 'menu/joinableGames',
      loadGamesStatus: 'menu/loadGamesStatus'
    })
  },
  mixins: [clickaway],
  created() {
    // When entering this component, fetch joignable games from server
    this.fetchJoinableGames();
  }
};
</script>
<style lang="scss" scoped>
.gamesListContainer {
  margin-left: 15%;
}
.gamesListContainer {
  font-family: MedievalSharp, cursive;
  color: #a41515;
}
</style>
