<template>
  <div>
    <h1>LOBBY</h1>

    <div id="error">{{ errorMessage }}</div>

    <form v-on:submit.prevent="newGame">
      <input
        type="text"
        autocomplete="off"
        required
        placeholder="what's your name?"
        v-model="newGameName"
        :disabled="loading"
        />
      <button type="submit" :disabled="loading">new game</button>
    </form>

    <p>or</p>

    <form v-on:submit.prevent="joinGame">
      <input
        type="text"
        autocomplete="off"
        required
        placeholder="join code"
        v-model="joinGameCode"
        :disabled="loading"
        />
      <input
        type="text"
        autocomplete="off"
        required
        placeholder="what's your name?"
        v-model="joinGameName"
        :disabled="loading"
        />
      <button type="submit" :disabled="loading">join game</button>
    </form>
  </div>
</template>

<script>
export default {
  name: "Lobby",

  data() {
    return {
      loading: false,
      newGameName: "",
      joinGameName: "",
      joinGameCode: "",
      errorMessage: "",
    };
  },

  methods: {
    newGame: function(evt) {
      this.loading = true;
      let name = this.newGameName;
      Meteor.call("newGame", { name }, (err, res) => {
        if (err !== undefined) {
          this.errorMessage = err.message;
          this.loading = false;
          return;
        }
        this.$emit("newGame", res);
      });
    },

    joinGame: function(evt) {
      this.loading = true;
      let name = this.joinGameName;
      let code = this.joinGameCode;
      Meteor.call("joinGame", { code, name }, (err, res) => {
        if (err !== undefined) {
          this.errorMessage = err.message;
          this.loading = false;
          return;
        }
        this.$emit("joinGame", res);
      });
    },
  }
}
</script>

<style scoped>
#error {
  color: red;
}
</style>
