<template>
  <div class="home">
    <md-field>
      <label>Name</label>
      <md-input v-model="name" :readonly="gameJoined"></md-input>
    </md-field>
    <md-field v-if="!gameStarted">
      <label>Game code</label>
      <md-input v-model="code" :readonly="gameJoined"></md-input>
    </md-field>
    <template v-if="!gameJoined">
      <md-button @click="createGame" class="md-raised">Create</md-button>
      <md-button @click="joinGame" class="md-raised">Join</md-button>
    </template>

    <template v-if="gameJoined && !gameStarted">
      <span v-if="owner">Game created!</span>
      <span v-else>Game joined!</span>
      <br>
      PlayerId: {{ playerId }} <br>

      <md-button v-if="owner" @click="startGame" class="md-raised md-primary">Start</md-button>
      <md-button v-else @click="checkStarted" class="md-raised md-primary">Check</md-button>
    </template>

    <template v-if="gameStarted">
      The game has started, lets go!
    </template>

    <HelloWorld msg="Welcome to Your Vue.js + TypeScript App"/>
  </div>
</template>

<script lang="ts">
import {Component, Vue} from 'vue-property-decorator'
import HelloWorld from '@/components/HelloWorld.vue'
import PerudoApi from "@/services/PerudoApi";
import {ApiObject, GameState, IsStartedObject, JoinCreateGameObject} from "@/objects/objects"; // @ is an alias to /src

@Component({
  components: {
    HelloWorld,
  }
})
export default class Home extends Vue {
  private gameState: GameState = GameState.Setup;

  private name: string = 'Bobby';
  private code: string = '';
  private owner: boolean = false;

  private playerId: string | null = null;

  private get gameJoined(): boolean {
    return this.gameState >= GameState.Joined;
  }

  private get gameStarted(): boolean {
    return this.gameState >= GameState.Started;
  }

  private createGame() {
    PerudoApi.instance.createGame(this.name).then((response: JoinCreateGameObject) => {
      this.playerId = response.player.id;
      this.code = response.code;
      this.owner = true;

      this.gameState = GameState.Joined;
    });
  }

  private joinGame() {
    PerudoApi.instance.joinGame(this.name, this.code).then((response: JoinCreateGameObject) => {
      this.playerId = response.player.id;

      this.gameState = GameState.Joined;
    })
  }

  private startGame() {
    if (this.playerId) {
      PerudoApi.instance.startGame(this.playerId).then((response: ApiObject) => {
        this.gameState = GameState.Started;
      })
    }
  }

  private checkStarted() {
    if (this.playerId) {
      PerudoApi.instance.startedGame(this.playerId).then((response: IsStartedObject) => {
        if (response.started) {
          this.gameState = GameState.Started;
        }
      });
    }
  }
}
</script>
