const fs = require('fs');
// @ts-ignore
const YUVBuffer = require('yuv-buffer');
// @ts-ignore
const YUVCanvas = require('yuv-canvas');

const {PlayerStatistics} = require('./playerstatistics');

export class YUVFilePlayer {
  constructor(canvas) {
    this.canvas = canvas;
    this.stats = new PlayerStatistics();
  }

  play(src, w, h, webgl, scale, cw, ch) {
    let fd = fs.openSync('raw/' + src, 'r+');
    let cnt = 0;
    const luma_len = w * hl;
    const chroma_len = luma_len / 4;
    const len = luma_len * 1.5;
    const format = YUVBuffer.format({
      width: w * 1,
      height: h * 1,
      chromaWidth: Math.round(w / 2),
      chromaHeight: Math.round(h / 2),
      displayWidth: scale ? cw : w * 1,
      displayHeight: scale ? ch : h * 1
      //cropWidth: w*1
    });
    const frame = YUVBuffer.frame(format);
    const yuvCanvas = YUVCanvas.attach(this.canvas, {webGL: webgl});

    setTimeout(function foo() {
      for (let i = 0; i < 2; i++) {
        const y_bytes = fs.readSync(fd, frame.y.bytes, 0, luma_len, null);
        const u_bytes = fs.readSync(fd, frame.u.bytes, 0, chroma_len, null);
        const v_bytes = fs.readSync(fd, frame.v.bytes, 0, chroma_len, null);

        if (y_bytes < luma_len || u_bytes < chroma_len || v_bytes < chroma_len) {
          fs.closeSync(fd);
          fd = fs.openSync('raw/' + src, 'r+');
        } else {
          break;
        }
      }

      yuvCanvas.drawFrame(frame);

      this.stats.updateStatistics.call(this.stats);
      //this.updateStatistics.call(this);
      cnt++;

      //if (cnt < 10000) {
      setTimeout(foo.bind(this), 0);
      //} else fs.closeSync(fd);
    }.bind(this), 0);
  }
}
