<template>
  <div class="row">
    <div class="col-12 col-md-8 offset-sm-2 col-lg-6 offset-md-3">
      <div id="online-games">
        Existing Games
        <hr />
        <div style="border:1px solid black; height:300px">
          <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>

      <div id="online-room-buttons">
        <div>
          <button class="btn btn-primary" @click="$emit('enter-game-creation')">
            Create new game
          </button>
          <button
            class="btn btn-primary"
            :disabled="resumeDisabled"
            @click="joinGame()"
          >
            Join / Resume game
          </button>
          <button class="btn btn-primary" @click="$emit('back')">Back</button>
        </div>
      </div>
    </div>
  </div>
</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>
// @import '../style/style.scss';
</style>
