const path = require('path');
const electron = require('electron');
const { fork } = require('child_process');
let children; //子进程实例
var app = electron.remote ? electron.remote.app : electron.app;
let cmdCallBack = {};
let heartbeatInteval = null;
let mainHdApi = {
  /* 硬件库初始化 */
  async hdHardWareInit(deviceList = [], cb, log, mainPath, dllpath, logPath, authorizationCode = '754a0b2598ffa1839ea165829918396d1a06967e7de87304') {
    if (log) {
      ktLog = log;
    }
    let childFile = path.join(__dirname, './hardware.js');
    if (app.isPackaged) {
      childFile = path.join(process.resourcesPath, './hardware.js');
    }
    ktLog.i('子进程路径：' + childFile);
    if (children) {
      await this.hdHardWareRelease();
    }
    try {
      children = fork(childFile, [], {
        detached: false,
      });
      ktLog.i('启动硬件库进程成功ID为：' + children.pid);
      if (heartbeatInteval) {
        clearInterval(heartbeatInteval);
      }
      heartbeatInteval = setInterval(() => {
        if (children) {
          children.send({ cmd: 'heartbeat' }, (error) => {
            if (error) {
              ktLog.i('往子进程发送心跳错误:' + error);
            }
          });
        } else {
          ktLog.i('子进程不存在');
        }
      }, 10 * 1000);
    } catch (error) {
      ktLog.i('启动硬件库子进程错误：' + error);
    }

    children.on('message', function (data) {
      switch (data.cmd) {
        case 'ktLog':
          ktLog.i(data.msg);
          break;
        case 'hdCall':
          ktLog.i(`硬件库返回：${JSON.stringify(data.data) || ''}`);
          if (data.data && cmdCallBack[data.data.cmd]) {
            cmdCallBack[data.data.cmd](data.data);
          } else {
            cb(data.data);
          }
        default:
          break;
      }
    });
    children.on('close', (code, signal) => {
      console.log('-------硬件库进程关闭----------', code, signal);
      if (signal && signal == 'SIGKILL') {
        ktLog.i(`主动关闭硬件库进程：${signal}`);
      } else {
        ktLog.i(`硬件库进程异常关闭三秒后重启硬件库进程：${signal ? signal : ''}`);

        setTimeout(() => {
          mainHdApi.hdHardWareInit(deviceList, cb, log, mainPath, dllpath, logPath, authorizationCode);
        }, 3000);
      }
      if (children && !children.connected) {
        children = null;
      }
    });
    childSend({
      cmd: 'hdHardWareInit',
      data: { deviceList, authorizationCode, dllpath, logPath, mainPath },
    });
  },

  /* 读取硬件库版本号 */
  hdHardWareVer(deviceList = []) {
    return new Promise((resolve, reject) => {
      childSend({
        cmd: 'hdHardWareVer',
        data: deviceList,
      });
      cmdCallBack.HardWareVer = (data) => {
        resolve(data);
      };
    });
  },

  /* 硬件指令 */
  hdHardWareCMD(cmdData) {
    return new Promise((resolve, reject) => {
      childSend({
        cmd: 'hdHardWareCMD',
        data: cmdData,
      });
      cmdCallBack[cmdData.cmd] = (result) => {
        resolve(result);
      };
    });
  },
  /* 释放硬件库 */
  hdHardWareRelease() {
    return new Promise((resolve, reject) => {
      childSend({
        cmd: 'hdHardWareRelease',
        data: {},
      });
      cmdCallBack.HardWareRelease = (data) => {
        if (children) {
          ktLog.i('关闭硬件库进程ID为：' + children.pid);
          children.kill('SIGKILL');
          children = null;
        }
        resolve(data);
      };
    });
  },
};
// 往子进程发送信息
function childSend(data) {
  try {
    if (data.data && data.data.cmd) {
      ktLog.i('调用硬件库API：:' + data.data.cmd);
    } else {
      ktLog.i('调用硬件库API：:' + data.cmd);
    }
  } catch (error) {
    ktLog.i(`往子进程发送信息：日志打印错误: ${error.message || error}`);
  }
  if (children) {
    children.send(data, (error) => {
      if (error) {
        ktLog.i('往子进程发送信息错误:' + error);
      }
    });
  } else {
    ktLog.i('子进程不存在');
  }
}
module.exports = mainHdApi;
