<template>
  <div id="player" :class="{fullscreen: fullscreen}">
    <div>
      <label for="zoom">Zoom:</label>
      <input type="number" min="1" :max="50" value="1" class="slider" v-model.number="zoom" id="zoom">
    </div>
    <div id="player-canvas-container">
      <canvas ref="canvas" id="player-canvas"
              :height="canvas_height" :width="canvas_width">
      </canvas>
    </div>
    <div id="controls" class="{'fullscreen-controls': fullscreen}">
      <div>
        <label for="recordMode">Record output</label>
        <input type="checkbox" v-model="record" id="recordMode">
      </div>
      <div>
        <input type="range" min="0" :max="frames - 1" value="0" class="slider"
               v-model.number="position" :disabled=record>
      </div>
      <div>
        <button @click="playPause">{{buttonLabel}}</button>
      </div>
      <div>
        <label for="sort">Sort by size</label>
        <input type="checkbox" v-model="sortBySize" id="sort">
      </div>
      <div>
        <label for="sortDirection">
          <span v-if="sortDirection">Ascending</span>
          <span v-else>Descending</span>
        </label>
        <input type="checkbox" v-model="sortDirection" id="sortDirection">
      </div>
    </div>
  </div>
</template>

<script>
import CCapture from "ccapture.js";
import bowser from "bowser";

export default {
  name: "player",
  props: {
    width: Number,
    height: Number,
  },
  data: function () {
    return {
      image: null,
      playing: false,
      zoom: 1,
      fullscreen: false,
      sortBySize: false,
      sortDirection: false,
      position: 0,
      tmp_ctx: null,
      animation_id: null,
      record: false,
      capturer: new CCapture({
        format: "webm",
        verbose: true,
      }),
    };
  },
  computed: {
    frames: function () {
      if (this.image === null) return 0;
      return Math.ceil(this.image.width / this.width) *
        Math.ceil(this.image.height / this.height);
    },
    canvas_height: function () {
      return this.height * this.zoom;
    },
    canvas_width: function () {
      return this.width * this.zoom;
    },
    frame_sequence: function () {
      if (this.image === null) return [];

      let sequence = [];
      for (let pos = 0; pos < this.frames; pos++) {
        let wb = Math.ceil(this.image.width / this.width); // width_blocks
        let x = (pos % wb) * this.width; // x offset
        let w = x + this.width < this.image.width ? this.width : this.image.width - x; // frame width
        let y = Math.floor(pos / wb) * this.height; // y offset
        let h = y + this.height < this.image.height ? this.height : this.image.height - y; // frame height
        sequence.push([x, y, w, h]);
      }
      if (this.sortBySize) {
        let tmpCanvas = document.createElement("canvas");
        let ctx = tmpCanvas.getContext("2d");
        let sizes = sequence.map((el, i) => {
          if (tmpCanvas.width !== el[2] ||
            tmpCanvas.height !== el[3]) {
            tmpCanvas.width = el[2];
            tmpCanvas.height = el[3];
          }
          ctx.drawImage(this.image, el[0], el[1], el[2], el[3],
            0, 0, el[2], el[3]);
          return {index: i, length: tmpCanvas.toDataURL("image/png").length};
        });

        sizes.sort(function (a, b) {
          return a.length - b.length;
        });

        if (!this.sortDirection) {
          sizes.reverse();
        }

        return sizes.map(function (el) {
          return sequence[el.index];
        });
      } else {
        return sequence;
      }
    },
    buttonLabel: function () {
      if (!this.playing) {
        if (this.record) {
          return "RECORD";
        } else {
          return "PLAY";
        }
      } else {
        return "STOP";
      }
    },
  },
  mounted: function () {
    this.$bus.$on("imageLoaded", (image) => {
      this.image = image;
    });
    this.clear("red");
  },
  watch: {
    canvas_width: function () {
      setTimeout(() => {
        this.clear("red");
      }, 0);
    },
    canvas_height: function () {
      setTimeout(() => {
        this.clear("red");
      }, 0);
    },
    position: function () {
      if (this.playing || this.image === null) return;
      this.tmp_ctx = this.$refs.canvas.getContext("2d");
      this.$render();
    },
    record: function () {
      if (this.record) {
        this.position = 0;
        if (!bowser.chrome) {
          alert("Recording only supported in Chrome :( \n" +
            "https://github.com/spite/ccapture.js/#limitations");
        }
      }
    },
  },
  methods: {
    playPause: function () {
      if (this.frames === 0) {
        return;
      }
      this.playing = !this.playing;
      if (this.playing) {
        this.tmp_ctx = this.$refs.canvas.getContext("2d");
        if (this.record) this.capturer.start();
        this.$render_advance();
      } else {
        cancelAnimationFrame(this.animation_id);
      }
    },
    clear: function (style) {
      let ctx = this.$refs.canvas.getContext("2d");
      ctx.fillStyle = style;
      ctx.fillRect(0, 0, parseInt(this.canvas_width), parseInt(this.canvas_height));
    },
    $render: function () {
      let frame = this.frame_sequence[this.position];
      if (frame === undefined) return;
      let [x, y, w, h] = frame;
      if (w !== this.width || h !== this.height) this.clear("black");
      this.tmp_ctx.drawImage(this.image,
        x, y, w, h,
        0, 0, w * this.zoom, h * this.zoom);
    },
    $render_advance: function () {
      this.$render();
      if (this.position < this.frames) {
        this.position += 1;
        this.animation_id = requestAnimationFrame(this.$render_advance);
        if (this.record) this.capturer.capture(this.$refs.canvas);
      } else {
        this.playPause();
        this.position = 0;
        if (this.record) {
          this.capturer.stop();
          this.capturer.save();
        }
      }
    },
  },
};
</script>

<style scoped>
#player {
  text-align: center;
}

.fullscreen {
  position: absolute;
  top: 0;
  left: 0;
  background-color: rgba(1, 1, 1, .9);
  width: 100%;
  height: 100%;
}

.fullscreen-controls {
  position: absolute;
  bottom: 0;
}

#zoom {
  width: 3em;
}
</style>
