var qrtool = null;
var qrtool_ready = false;

function load_qrtool() {
  var m = require('/assets/qrtool.wx.js');
  // Set WASM file path for web context
  m['setWasmPath']('/assets/qrtool.wx.wasm');
  m.onRuntimeInitialized = () => {
    console.log("runtime initialized");
    qrtool_ready = true;
    qrtool = m;
  }
}

function frame_pre_check(width, height, uca, camera_sensitivity) {
  var r;
  if (!qrtool_ready) {
    console.log("qrtool not ready");
    return -1;
  }
  var buf = qrtool._malloc(uca.length * uca.BYTES_PER_ELEMENT);
  qrtool.HEAPU8.set(uca, buf);
  const dot_area_size = 32;
  const da_len = dot_area_size * dot_area_size * uca.BYTES_PER_ELEMENT * 4;
  var dot_area_buf = qrtool._malloc(da_len)
  r = qrtool.ccall('qrtool_angle', 'string', ['number', 'number', 'number', 'number', 'number'], [buf, width, height, dot_area_buf, camera_sensitivity]);
  // r = qrtool.ccall('qrtool_angle', 'string', ['number', 'number', 'number', 'number'], [buf, width, height, 0]);
  var view = qrtool.HEAPU8.subarray(dot_area_buf, dot_area_buf + da_len);
  console.log("view begin", view[0], view[1], view[2], view[3]);
  const a = da_len - 8;
  console.log("view end", view[a + 0], view[a + 1], view[a + 2], view[a + 3]);
  const data_url = data_url_from_frame(dot_area_size, dot_area_size, view);
  qrtool._free(buf);
  qrtool._free(dot_area_buf);
  return {
    result: JSON.parse(r),
    data_url,
  }
}

const offscreenCanvas = wx.createOffscreenCanvas({
    type: '2d',
    width: 100,
    height: 100,
});

function data_url_from_frame(width, height, uca) {
  offscreenCanvas.width = width;
  offscreenCanvas.height = height;
  var ctx = offscreenCanvas.getContext('2d')
  var imgd = ctx.createImageData(width, height);
  imgd.data.set(uca);
  ctx.putImageData(imgd, 0, 0);
  return offscreenCanvas.toDataURL("image/jpeg", 1.0);
}

function is_emblem_qr_pattern(p)
{
  if (p.search(/code=[0-9a-zA-Z]+/) >= 0) return true;
  if (p.search(/c=[0-9a-zA-Z]+/) >= 0) return true;
  if (p.search(/https:\/\/xy.ltd\/v\/[0-9a-zA-Z]+/) >= 0) return true;
  return false;
}

module.exports = {
  data_url_from_frame,
  frame_pre_check,
  load_qrtool,
  is_emblem_qr_pattern,
};
