function check_auto_torch(qrcode, server_url, cb) {
  var url = server_url + '/api/v1/check-auto-torch/?qrcode=' + encodeURIComponent(qrcode);
  console.log("check_auto_torch:", url);
  const fail = (e) => {
    console.log("failed to check auto torch", e);
    cb(false, null);
  };
  const success = (res) => {
    if (res.statusCode == 200) {
      var resp;
      console.log(res.data);
      if (typeof res.data == "string") {
        resp = JSON.parse(res.data);
      } else {
        resp = res.data;
      }
      cb(resp.enable_auto_torch, resp.camera_sensitivity);
    } else {
      console.log("failed to check auto torch", res.data);
      cb(false, null);
    }
  };
  wx.request({
    url,
    method: "GET",
    success,
    fail,
  });
}

function upload_image_data_urls(image_data_urls, success, fail, log, real_ip, qr_code, phone_model, server_url, caller_info) {
    var ui = wx.getStorageSync('userinfo');
    var fd = {
        emblem_id: ui.emblem_id,
        nick_name: ui.nickName,
        realip: real_ip,
        qrcode: qr_code,
        angle: 0,
        phonemodel: phone_model,
        image_data_urls,
        use_roi_verify: 1,
        log,
    };
    var ci = caller_info;
    if (ci && ci.token) {
        fd.token = ci.token;
    }
    var url = server_url + '/api/v1/qr-verify/';
    console.log("wx.request", url, fd.qrcode, fd.angle, fd.phonemodel, fd.realip);
    wx.request({
      url,
      method: "POST",
      header: {
        "Content-Type": "application/json",
      },
      data: JSON.stringify(fd),
      success,
      fail,
    });
}

function upload_image_data_urls_with_metadata(image_data_urls, qrcode, metadata, success, fail, log, caller_info) {
    var fd = {
        emblem_id: metadata.userinfo.emblem_id,
        nick_name: metadata.userinfo.nickName,
        realip: metadata.real_ip,
        qrcode: qrcode,
        angle: 0,
        phonemodel: metadata.phone_model,
        image_data_urls,
        use_roi_verify: 1,
        log,
    };
    var ci = caller_info;
    if (ci && ci.token) {
        fd.token = ci.token;
    }
    var url = metadata.server_url + '/api/v1/qr-verify/';
    console.log("wx.request", url, fd.qrcode, fd.angle, fd.phonemodel, fd.realip);
    wx.request({
      url,
      method: "POST",
      header: {
        "Content-Type": "application/json",
      },
      data: JSON.stringify(fd),
      success,
      fail,
    });
}

module.exports = {
  upload_image_data_urls,
  upload_image_data_urls_with_metadata,
  check_auto_torch,
};