<template>
  <div id="player">
    <div>
      <label for="zoom">Zoom:</label>
      <input type="number" min="0.1" value="1" step="0.1" class="slider" v-model.number="zoom" id="zoom">
    </div>
    <div class="player-container">
      <canvas ref="canvas" id="player-canvas"
              :height="canvas_height" :width="canvas_width">
      </canvas>
      <div>
        <input type="range" min="0" :max="frames - 1" value="0" class="slider"
               v-model.number="position" :disabled=recording>
      </div>
    </div>
    <div class="controls">
      <div>
        <button @click="playOnceOrPause">{{!this.playing ? "PLAY ONCE" : "STOP"}}</button>
      </div>
      <div>
        <button @click="recordSequence">RECORD</button>
      </div>
      <div>
        <button @click="loopFullscreen">LOOP & FULLSCREEN</button>
      </div>
    </div>
    <div class="options">
      <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>
        <label for="discard">Discard partial frames</label>
        <input type="checkbox" v-model="discardPartial" id="discard">
      </div>
    </div>
  </div>
</template>

<script>

export default {
  name: "player",
  props: {
    width: Number,
    height: Number,
    offset: Array,
  },
  data: function () {
    return {
      image: null,
      playing: false,
      zoom: 1,
      recording: false,
      looping: false,
      sortBySize: false,
      sortDirection: false,
      discardPartial: false,
      position: 0,
      tmp_ctx: null,
      animation_id: null,
      recorder: null,
    };
  },
  computed: {
    frames: function () {
      if (this.image === null) return 0;
      const roundFn = this.discardPartial ? Math.floor : Math.ceil;
      return roundFn((this.image.width - this.offset[0]) / this.width) * roundFn((this.image.height - this.offset[1]) / 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 = (this.discardPartial ? Math.floor : Math.ceil)((this.image.width - this.offset[0]) / this.width); // width_blocks
        let x = this.offset[0] + (pos % wb) * this.width; // x offset
        let w = x + this.width < this.image.width ? this.width : this.image.width - x; // frame width
        let y = this.offset[1] + 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;
      }
    },
  },
  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);
    },
    frames: function () {
      this.$emit("frames", this.frames);
    },
    position: function () {
      if (this.playing || this.image === null) return;
      this.tmp_ctx = this.$refs.canvas.getContext("2d");
      this.$render();
    },
    looping: function () {
      this.recording = false;
    },
    recording: function () {
      if (this.recording) {
        this.looping = false;
        this.position = 0;
      }
    },
  },
  methods: {
    play: function () {
      if (this.frames === 0) {
        return;
      }
      if (!this.playing) {
        // eslint-disable-next-line no-console
        console.log("STARTED");
        this.tmp_ctx = this.$refs.canvas.getContext("2d");
        this.$render_advance();
        this.playing = true;
      }
    },
    stop: function () {
      if (this.playing) {
        // eslint-disable-next-line no-console
        console.log("STOPPED");
        cancelAnimationFrame(this.animation_id);
        this.playing = false;
        if (this.recording && this.recorder) {
          this.recorder.stop();
          this.recording = false;
        }
      }
    },
    playOnceOrPause: function () {
      if (!this.playing) {
        this.looping = false;
        this.recording = false;
        this.position = 0;
        this.play();
      } else {
        this.stop();
      }
    },
    recordSequence: function () {
      try {
        this.createRecorder();
      } catch (err) {
        alert("Error initializing recording!\n" + err);
        return;
      }
      this.looping = false;
      this.recording = true;
      this.stop();
      this.position = 0;
      this.recorder.start();
      this.play();
    },
    loopFullscreen: function () {
      this.play();
      this.looping = true;
      this.recording = false;
      document.getElementById("player-canvas").requestFullscreen();
    },
    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_advance: function () {
      this.$render();
      if (this.position < this.frames) {
        this.position += 1;
        this.animation_id = requestAnimationFrame(this.$render_advance);
      } else {
        if (!this.looping) {
          this.stop();
        } else {
          this.animation_id = requestAnimationFrame(this.$render_advance);
        }
        this.position = 0;
      }
    },
    $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);
    },
    createRecorder: function () {
      const stream = this.$refs.canvas.captureStream();
      this.recorder = new MediaRecorder(stream, {mimeType: "video/webm"});
      if (!this.recorder) {
        throw new Error("Unknown error, couldn't initialize recorder.");
      }
      this.recorder.ondataavailable = function (event) {
        if (!event.data) {
          alert.error("Error during recording: No data available!");
          return;
        }
        const blob = new Blob([event.data], {type: "video/webm"});
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.style.display = "none";
        a.href = url;
        a.download = "slitscan.webm";
        document.body.appendChild(a);
        a.click();
        setTimeout(() => {
          document.body.removeChild(a);
          window.URL.revokeObjectURL(url);
        }, 100);
      };
    },
  },
};
</script>

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

#zoom {
  width: 3em;
  text-align: center;
}

.player-container {
  padding: 2em 0 1em 0;
}

.controls, .options {
  display: flex;
  flex-direction: column;
}

.controls button {
  width: 12em;
  margin: .25em;
}

.options {
  padding-top: 1em;
}

.options div {
  display: flex;
  justify-content: space-between;
}
</style>
