console.log("hello from worker");

let qrtool = require('qrtool.wx.js');

var qrtool_ready = false;

qrtool.onRuntimeInitialized = () => {
  console.log("qrtool ready");
  qrtool_ready = true;
  worker.postMessage({
    type: "ready",
  });
}

var submit_message = null;

function handle_frame(data, width, height, camera_sensitivity) {
  if (!qrtool_ready) {
    console.log("qrtool not ready");
    worker.postMessage({
      type: "result",
      res: {
        ok: false,
        err: "qrtool not ready",
      },
      processing_time: Date.now() - begin,
    });
    return;
  }
  const begin = Date.now();
  var uca = new Uint8ClampedArray(data);
  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("r:", r);
  var res = JSON.parse(r);
  worker.postMessage({
    type: "result",
    res,
    processing_time: Date.now() - begin,
  });
  if (res.ok) {
    // Since image_data takes seconds to serialize, send it in a separate
    // message to the UI can update with the good news
    submit_message = {
      type: "submit",
      res,
      image_data: { data, width, height },
    };
  }
}

worker.onMessage((msg) => {
  console.log("worker got message", msg.type);
  switch (msg.type) {
    case "frame":
      try {
        const data = worker.getCameraFrameData();
        if (data) {
          handle_frame(data, msg.width, msg.height, msg.camera_sensitivity);
        }
      } catch (e) {
        console.log(e);
      }
    break;
    case "ready_to_submit":
      worker.postMessage(submit_message);
    break;
    default:
      console.log("Unknown message type:", msg.data.type);
  }
});
