const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

function get_system_info() {
  return wx.getSystemInfoSync();
}

function get_phone_model() {
  var ret = get_system_info().model;
  console.log("phone model", ret);
  return ret;
}

function match_camera_rules(model, rules, default_zoom) {
  console.log(model, "apply zoom rules:", rules);
  var best_match = null;
  for (var rule of rules) {
    if (model.toLowerCase().startsWith(rule.model.toLowerCase())) {
      if (!best_match || rule.model.length > best_match.model.length) {
        best_match = rule;
      }
    }
  }
  if (best_match) {
    console.log("found best match", best_match);
    return best_match;
  }
  var ret = {
    zoom: default_zoom,
    web_view: false
  };
  console.log("using default", ret);
  return ret;
}

var camera_rules = null;

function get_camera_rule(max_zoom, cb) {
  var default_zoom = 4;
  if (max_zoom && max_zoom >= 60) {
    /*
     * 2024.06.01: in some Huawei/Honor models, the scale is different, use 40
     * in this case so we don't need to set up rules for each specific model
     */
    console.log(`max zoom is ${max_zoom}, default zoom will be 40`);
    default_zoom = 40;
  }
  if (camera_rules) {
    let rule = match_camera_rules(get_phone_model(), camera_rules, default_zoom);
    cb(rule);
  } else {
    var url = 'https://themblem.com/api/v1/camera-rules/';
    var r = wx.request({
      url,
      complete: (res) => {
        var rules = res.data;
        camera_rules = rules;
        let rule = match_camera_rules(get_phone_model(), rules, default_zoom);
        cb(rule);
      }
    });
  }
}

function goto_camera(redirect, opts) {
  var query = opts || "";
  // Route to emblemscanner with return page for product info
  var url = "/pages/emblemscanner/emblemscanner?return_page=/pages/productinfo/productinfo";
  if (query) {
    url += "&" + query;
  }
  if (redirect) {
    wx.redirectTo({ url });
  } else {
    wx.navigateTo({ url });
  }
}

function make_new_session_id() {
  return `${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;
}

function send_event(event_name, data, success_cb, fail_cb) {
  wx.request({
    url: 'https://research.themblem.com/event/' + event_name,
    method: 'POST',
    data: JSON.stringify(data),
    header: {
      'Content-Type': 'application/json',
    },
    success: success_cb,
    fail: fail_cb,
  });
}

function extract_code_from_url(url) {
  /*
def get_code_from_url(url):
    code = None
    patterns = [
            '[?&]code=([0-9a-zA-Z]+)',
            '[?&]c=([0-9a-zA-Z]+)',
            'xy.ltd/v/([0-9a-zA-Z]+)'
    ]
    for p in patterns:
        m = re.search(p, url)
        if m:
            return m.group(1)
            */
  var patterns = [
    /[?&]code=([0-9a-zA-Z]+)/,
    /[?&]c=([0-9a-zA-Z]+)/,
    /xy\.ltd\/v\/([0-9a-zA-Z]+)/,
  ];
  for (var p of patterns) {
    var code_match = url.match(p);
    if (code_match) {
      return code_match[1];
    }
  }
  return null;
}

module.exports = {
  get_system_info,
  get_phone_model,
  get_camera_rule,
  goto_camera,
  formatTime,
  make_new_session_id,
  send_event,
  extract_code_from_url,
}

