<template>
  <div id="gameContainer" :style="containerStyle"></div>
</template>
<script>
import phaserGames from "./phaser/index";
import h5games from "./h5/index";

const games = { ...phaserGames, ...h5games };
const STATE_RUNNING = 0;
const STATE_LOSE = 1;
const STATE_WON = 2;
const STATE_PAUSED = 3;
export default {
  props: ["name", "containerStyle", "debug"],
  data() {
    return {
      state: STATE_RUNNING,
      game: null,
      containerId: "gameContainer",
    };
  },
  watch: {
    name(val, oldVal) {
      if (oldVal) {
        this.dispose();
        this.reload(val);
      }
    },
  },
  methods: {
    pause() {
      this.game.pause();
      this.state = STATE_PAUSED;
      this.$emit("paused");
    },
    resume() {
      if (this.state === STATE_PAUSED) {
        this.game.resume();
        this.state = STATE_RUNNING;
        this.$emit("resumed");
      }
    },
    restart() {
      this.game.restart();
      this.state = STATE_RUNNING;
    },
    dispose() {
      this.game.dispose();
      const container = document.getElementById("gameContainer");
      container && (container.innerHTML = "");
    },
    reload(name) {
      this.game = new games[name]({
        containerId: this.containerId,
        onLose: () => {
          if (this.state !== STATE_LOSE) this.$emit("lost");
          this.state = STATE_LOSE;
        },
        onWon: () => {
          if (this.state !== STATE_WON) this.$emit("won");
          this.state = STATE_WON;
        },
      });
    },
  },
  async mounted() {
    this.reload(this.name);
  },

  destroyed() {
    this.dispose();
  },
};
</script>

<style>
</style>