import XMLHttpRequest from 'xhr2';
var xhr = new XMLHttpRequest();


function loadScript() {
  import("./gs.js");
}

let Module;

/**
 * Process a PDF with custom Ghostscript arguments.
 *
 * @param {Array} ghostscriptArgs - The array of Ghostscript command-line arguments to perform the operation.
 * @param {Blob|File} file - The input PDF file object (Blob or File).
 * @param {Function} responseCallback - Called with the response containing the processed PDF URL.
 * @param {Function} progressCallback - Called to report progress.
 * @param {Function} statusUpdateCallback - Called to report status updates.
 */
export function _processPDF(
  ghostscriptArgs,
  file, // Input file must be of type Blob or File
  responseCallback,
  progressCallback,
  statusUpdateCallback
) {
  console.log("Ghostscript Args:", ghostscriptArgs);
  console.log("Processing File:", file.name || "Unknown");

  const reader = new FileReader();

  // Ensure file is of type Blob or File
  if (!(file instanceof Blob || file instanceof File)) {
    console.error("Passed file is not a valid Blob or File.");
    return;
  }

  // Read the file content as an ArrayBuffer
  reader.onload = function (event) {
    const pdfArrayBuffer = event.target.result;
    console.log("PDF loaded successfully from file");

    // Set up EMScripten Module and processing logic
    Module = {
      preRun: [
        function () {
          const FS = window.FS;
          FS.writeFile("input.pdf", new Uint8Array(pdfArrayBuffer)); // Write input PDF to the filesystem
        },
      ],
      postRun: [
        function () {
          console.log("Ghostscript processing complete");
          const FS = window.FS;
          const outputFileName = ghostscriptArgs
            .find((arg) => arg.startsWith("-sOutputFile="))
            .split("=")[1]; // Extract output filename

          console.log("Output File Name:", outputFileName);
          const uarray = FS.readFile(outputFileName, { encoding: "binary" });
          const blob = new Blob([uarray], { type: "application/octet-stream" });
          const pdfDataURL = window.URL.createObjectURL(blob);
          responseCallback({ pdfDataURL, url: file.name });
        },
      ],
      arguments: ghostscriptArgs, // Pass the custom Ghostscript arguments
      print: function (text) {
        statusUpdateCallback(text);
      },
      printErr: function (text) {
        statusUpdateCallback("Error: " + text);
        console.error(text);
      },
      setStatus: function (text) {
        if (!Module.setStatus.last) Module.setStatus.last = { time: Date.now(), text: "" };
        if (text === Module.setStatus.last.text) return;
        const now = Date.now();
        Module.setStatus.last.time = now;
        Module.setStatus.last.text = text;
        const m = text.match(/([^(]+)\((\d+(\.\d+)?)\/(\d+)\)/);
        if (m) {
          progressCallback(false, parseInt(m[2]) * 100, parseInt(m[4]) * 100);
        } else {
          progressCallback(true, 0, 0);
        }
        statusUpdateCallback(text);
      },
      totalDependencies: 0,
    };

    Module.setStatus("Loading Ghostscript...");
    window.Module = Module;
    loadScript(); // Load the Ghostscript library (gs.js)
  };

  reader.onerror = function () {
    console.error("Failed to read file.");
  };

  reader.readAsArrayBuffer(file); // Read the PDF file as ArrayBuffer
}
