const { applyPatch } = require("diff");
const fs = require("fs");
const util = require("node:util");
const exec = util.promisify(require("node:child_process").exec);
const readline = require("readline");

const outPath =
  "./PackageSources/html_ui/Pages/VCockpit/Instruments/aircraft_efb/KH_TFDi_MD11_efb";

fs.copyFileSync("./EFB/efb.css", `${outPath}/efb.css`);

let file1Contents = fs.readFileSync("./EFB/efb.js").toString();
let patch = fs.readFileSync("./EFB/efb-js.patch").toString();
let patchedFile = applyPatch(file1Contents, patch);
fs.writeFileSync(`${outPath}/efb.js`, patchedFile);

file1Contents = fs.readFileSync("./EFB/efb.index.js").toString();
patch = fs.readFileSync("./EFB/efb-index-js.patch").toString();
patchedFile = applyPatch(file1Contents, patch);
fs.writeFileSync(`${outPath}/efb.index.js`, patchedFile);

file1Contents = fs.readFileSync("./EFB/efb.html").toString();
patch = fs.readFileSync("./EFB/efb-html.patch").toString();
patchedFile = applyPatch(file1Contents, patch);
fs.writeFileSync(`${outPath}/efb.html`, patchedFile);

var output = "";
var lineReader = readline.createInterface({
  input: fs.createReadStream(`${outPath}/App.js`),
});
lineReader.on("line", (line) => {
  if (line.startsWith("import")) {
    output += "// " + line + "\n";
  } else if (line.startsWith("export")) {
    output += "window.KH_LM = App;\n";
  } else {
    output += line + "\n";
  }
});
lineReader.on("close", () => {
  fs.writeFile(`${outPath}/App.js`, output, (err) => {
    if (err) console.log(err);
    console.log("Import/Export removed.");
  });
});
