let mainHdApi;
let cmdCallBack = {};
let ktLog = {
  i(msg) {
    console.log(msg);
  },
};

/**
 * 硬件库初始化
 * @param {*} deviceList   设备列表
 * @param {*} cb               回调
 * @param {*} log              日志
 * @param {*} mainPath    主库路径
 * @param {*} dllpath        字库库路径
 * @param {*} logPath       日志路径
 * @param {*} authorizationCode  授权码（可不传）
 */
function hdHardWareInit(deviceList = [], cb, log,  mainPath, dllpath, logPath,authorizationCode = '754a0b2598ffa1839ea165829918396d1a06967e7de87304') {
  if (log) {
    ktLog = log;
  }
  mainHdApi = window.require(mainPath);
  deviceList = JSON.stringify({ deviceList });
  ktLog.i(`硬件库初始化： \n authorizationCode=${authorizationCode} \n dllpath=${dllpath} \n logPath=${logPath} \n deviceList=${deviceList}`);
  mainHdApi.hdHardWareInit(authorizationCode, dllpath, logPath, deviceList, (res) => {
    ktLog.i(`执行硬件库回调：${res}`);
    res = JSON.parse(res);
    if (res && res.cmd && cmdCallBack[res.cmd]) {
      cmdCallBack[res.cmd](res);
    } else {
      cb(res);
    }
  });
}

/* 读取硬件库版本号 */
function hdHardWareVer(deviceList = []) {
  return new Promise((resolve) => {
    deviceList = JSON.stringify({
      deviceList: ['mainHardWare', ...deviceList],
    });
    ktLog.i(`获取硬件库版本号：${deviceList}`);
    // 硬件库版本号
    mainHdApi.hdHardWareVer(deviceList);
    cmdCallBack.HardWareVer = (result) => {
      ktLog.i(`硬件库版本号返回：${JSON.stringify(result)}`);
      const { resultCode, resultData } = result;
      if (resultCode === 1 && resultData) {
        resolve(resultData);
      }
      resolve('');
    };
  });
}

/**
 * 发送硬件指令
 * @param {*} cmdData 指令数据详情查看硬件库文档
 * @returns 
 */
function hdHardWareCMD(cmdData) {
  return new Promise((resolve) => {
    cmdCallBack[cmdData.cmd] = (result) => {
      resolve(result);
    };
    try {
      ktLog.i(`调用硬件库API：${cmdData.cmd}`);
    } catch (error) {
      ktLog.i(`调用硬件库API：日志打印错误: ${error.message || error}`);
    }
    cmdData = JSON.stringify(cmdData);
    mainHdApi.hdHardWareCMD(cmdData);
  });
}

/* 释放硬件库 */
function hdHardWareRelease() {
  return new Promise((resolve) => {
    mainHdApi.hdHardWareRelease();
    cmdCallBack.HardWareRelease = (result) => {
      ktLog.i(`硬件库释放：${JSON.stringify(result) || ''}`);
      resolve(result);
    };
  });
}
module.exports = {
  hdHardWareInit,
  hdHardWareCMD,
  hdHardWareRelease,
  hdHardWareVer
};
