console.log("hello from emblemscanner worker");

// Load qrtool module first - WASM path will be set via message
let qrtool = require('./qrtool.wx.js');
let wasmPathReceived = false;

console.log("QRTool loaded, waiting for WASM path via message...");



var qrtool_ready = false;

qrtool.onRuntimeInitialized = () => {
  console.log("emblemscanner qrtool ready");
  qrtool_ready = true;
  if (wasmPathReceived) {
    console.log("QRTool initialized successfully with WASM path");
    worker.postMessage({
      type: "ready",
    });
  } else {
    console.log("QRTool initialized but WASM path not received yet");
  }
}

var submit_message = null;

function handle_frame(data, width, height, camera_sensitivity) {
  const begin = Date.now();
  console.log(`handling frame ${width}x${height}, data is ${data.byteLength} bytes`);
  var uca = new Uint8ClampedArray(data);
  console.log(`first 4 bytes of uca: ${uca[0]}, ${uca[1]}, ${uca[2]}, ${uca[3]}`);
  var buf = qrtool._malloc(uca.length * uca.BYTES_PER_ELEMENT);
  qrtool.HEAPU8.set(uca, buf);
  var r = qrtool.ccall('qrtool_angle', 'string', ['number', 'number', 'number', 'number', 'number'], [buf, width, height, 0, camera_sensitivity]);
  qrtool._free(buf);
  console.log(`image ${width}x${height} processed in ${Date.now() - begin}ms, result: ${r}`);
  var res = JSON.parse(r);
  worker.postMessage({
    type: "result",
    res,
    processing_time: Date.now() - begin,
  });
  if (res.ok) {
    // Send raw image data back to main thread for data URL conversion
    // since we have no access to offscreen canvas in WASM worker
    submit_message = {
      type: "submit",
      res,
      image_data: { data, width, height },
    };
  }
}

worker.onMessage((msg) => {
  console.log("emblemscanner worker got message", msg.type);

  // Handle WASM path message for initialization
  if (msg.type === "wasm_path" && msg.path) {
    console.log("Received WASM path via message:", msg.path);
    if (typeof qrtool !== "undefined" && qrtool['setWasmPath']) {
      qrtool['setWasmPath'](msg.path);
      wasmPathReceived = true;
      console.log("WASM path set via message");

      // If qrtool is already ready, send ready message immediately
      if (qrtool_ready) {
        console.log("QRTool is already ready, sending ready message");
        worker.postMessage({
          type: "ready",
        });
      } else {
        console.log("Waiting for qrtool to become ready...");
      }
    }
    return; // Don't process further until qrtool is ready
  }

  // If WASM path hasn't been received yet, return error
  if (!wasmPathReceived) {
    console.log("WASM path not received yet, cannot process messages");
    worker.postMessage({
      type: "result",
      res: {
        ok: false,
        err: "wasm_path not received yet",
      },
      processing_time: 0,
    });
    return;
  }

  if (!qrtool_ready) {
    console.log("qrtool not ready");
    worker.postMessage({
      type: "result",
      res: {
        ok: false,
        err: "qrtool not ready",
      },
      processing_time: 0,
    });
    return;
  }
  switch (msg.type) {
    case "frame":
      try {
        const data = worker.getCameraFrameData();
        if (data) {
          handle_frame(data, msg.width, msg.height, msg.camera_sensitivity);
        } else {
          worker.postMessage({
            type: "result",
            res: {
              ok: false,
              err: "no frame data",
            },
          });
        }
      } catch (e) {
        worker.postMessage({
          type: "result",
          res: {
            ok: false,
            err: `failed to handle frame: ${e.message}`,
          },
        });
        console.log(e);
      }
    break;
    case "ready_to_submit":
      worker.postMessage(submit_message);
    break;
    default:
      console.log("Unknown message type:", msg.type);
  }
});