const { genFfmpegFormatConfigs } = require("./configs");
const child_process = require("child_process");
const EventEmitter = require("events");

class Mpeg1Muxer extends EventEmitter {
  constructor(options) {
    super(options);

    this.url = options.url;
    this.port = options.port;
  }

  onOutData(data) {
    return this.emit("mpeg1data", data);
  }

  onErrData(data) {
    return this.emit("ffmpegError", data);
  }

  setup() {
    this.stream = child_process.spawn(
      "ffmpeg",
      genFfmpegFormatConfigs(this.url, this.port),
      {
        detached: false,
      }
    );

    this.inputStreamStarted = true;
    this.stream.stdout.addListener("data", this.onOutData);
    this.stream.stderr.addListener("data", this.onErrData);
  }

  kill() {
    this.stream.stdout.removeListener("data", this.onOutData);
    this.stream.stderr.removeListener("data", this.onErrData);
    this.stream.stdout.destroy();
    this.stream.stderr.destroy();
    this.stream.kill();
    this.stream = null;
  }

  restart() {
    this.kill();
    this.setup();
  }
}

module.exports = Mpeg1Muxer;
