function upload_image_data_url(image_data_url, success, fail, log) {
  do_upload(image_data_url, success, fail, log);
}

function check_auto_torch(qrcode, cb) {
  var gd = getApp().globalData;
  var url = gd.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 do_upload(image_data_url, success, fail, log) {
    var ui = wx.getStorageSync('userinfo');
    var gd = getApp().globalData;
    var fd = {
        emblem_id: ui.emblem_id,
        nick_name: ui.nickName,
        realip: gd.real_ip,
        qrcode: gd.qr_code,
        angle: gd.angle,
        phonemodel: gd.phone_model,
        image_data_url,
        log,
    };
    var ci = gd.caller_info;
    if (ci && ci.token) {
        fd.token = ci.token;
    }
    var url = gd.server_url + '/api/v1/qr-verify/';
    if (gd.debug) {
        url = "https://themblem.com/api/v1/debug-upload/";
    }
    console.log("wx.request", url, fd.qrcode, fd.angle, fd.phonemodel, fd.realip);
    wx.request({
      url,
      method: "POST",
      data: fd,
      success,
      fail,
    });
}

module.exports = {
  upload_image_data_url,
  check_auto_torch,
};
