import path from "path";
import ffmpeg from "fluent-ffmpeg";
import { defer } from "../lib/api.js";

import logging from "../lib/logging.js";
const log = logging.create("commands/convert.js");

export const description = "Quickly fix an mp4 that's not streamable.";

export const options = [
  ["--input <infile>", "input .mp4 file to convert"],
  ["--output <outfile>", "output .mp4 file to convert"],
  ["--progress", "show progress (not accurate)", false],
  ["--debug <level>", "1=print ffmpeg cli, 2=and its stderr output"],
]

export const main = (opts) => {
  const encode_defer = defer();

  const encode = ffmpeg(opts.input)
    .videoCodec("copy")
    .audioCodec("copy")
    .outputOptions(["-movflags", "faststart"])
    .output(opts.output);

  if(opts.progress) {
    encode.on("progress", (progress) => {
      process.stdout.write(`${path.basename(opts.input)} -> ${ opts.output } ${Math.round(progress.percent)}%  \r`)
    });
  }

  if(opts.debug) {
    encode.on("start", line => console.log("FFMPEG: ", line));

    if(opts.debug == 2) {
      encode.on("stderr", line => console.log(line));
    }
  }

  encode.on("end", () => encode_defer.resolve());

  encode.run();
}
