<template>
  <b-container class="gamesListContainer">
    <b-row>
      <b-col cols="auto">
        <h1>
          Existing Games
        </h1>
        <div id="online-games">
          <div v-if="loading">
            <h3>{{ loadingMessage }}</h3>
          </div>
          <div v-on-clickaway="unselect" v-else>
            <game-item
              v-for="(game, index) in gamesList"
              :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()">
              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 { socketService, socketEventBus } from '../../main';
export default {
  props: ['username'],
  data() {
    return {
      selectedIndex: -1,
      resumeDisabled: true,
      loading: true,
      loadingMessage: 'Loading...',
      gamesList: []
    };
  },
  components: {
    GameItem
  },
  watch: {
    selectedIndex() {
      console.log('index selected: ' + this.selectedIndex);
      if (this.selectedIndex >= 0) {
        this.resumeDisabled = false;
      } else {
        this.resumeDisabled = true;
      }
    }
  },
  methods: {
    unselect() {
      this.selectedIndex = -1;
    },
    joinGame() {
      this.$emit('back');
      this.$emit('join-game-id', {
        id: this.gamesList[this.selectedIndex].id,
        username: this.username
      });
    },
    updateGamesList() {
      socketService
        .getGamesList(this.username)
        .then(games => {
          this.gamesList = games;
          if (this.gamesList.length === 0) {
            this.loadingMessage = 'No games found, wait a new or create one !';
          } else {
            this.loading = false;
          }
        })
        .catch(() => {
          this.loadingMessage = 'Error reaching server';
        });
    }
  },
  mixins: [clickaway],
  created() {
    this.updateGamesList();
    socketEventBus.$on('reload-games', () => {
      this.updateGamesList();
    });
  }
};
</script>
<style lang="scss" scoped>
.gamesListContainer {
  margin-left: 15%;
}
.gamesListContainer {
  font-family: MedievalSharp, cursive;
  color: #a41515;
}
</style>
