/*
 * 如果启用了上下文隔离，渲染进程无法使用electron的api，
 * 可通过contextBridge 导出api给渲染进程使用
 */

const { contextBridge, ipcRenderer } = require("electron");
const os = require("os");
const path = require("path");
const fs = require("fs");
const { v4: uuidv4 } = require("uuid");
const execs = require("child_process").exec;

const isDev = process.env.NODE_ENV === "development";

const isRunning = (query: string, cb: Function) => {
  // let platform = process.platform;
  // let cmd = "";
  // switch (platform) {
  //   case "win32":
  //     cmd = `tasklist`;
  //     break;
  //   case "darwin":
  //     cmd = `ps -ax | grep ${query}`;
  //     break;
  //   case "linux":
  //     cmd = `ps -A`;
  //     break;
  //   default:
  //     break;
  // }
  execs(
    "cmd /c chcp 65001>nul && tasklist /FO CSV",
    (err: any, stdout: any, stderr: any) => {
      cb(stdout.toLowerCase().indexOf(query.toLowerCase()) > -1);
    }
  );
};

contextBridge.exposeInMainWorld("electronApi", {
  getComputerName: () => {
    return os.hostname();
  },
  changeWinSize: (type: "big" | "small") => {
    ipcRenderer.send("change-win-size", type);
  },
  windowMin: () => {
    ipcRenderer.send("window-min");
  },
  startScanExe: (arr: string[]) => {
    let scanExeFold: string = isDev
      ? process.cwd()
      : process.env.PORTABLE_EXECUTABLE_DIR || "";
    const exePath = path.join(scanExeFold as string, "client.exe");
    console.log("exePath", exePath);
    ipcRenderer.send("startExe", exePath + " " + arr.join(" "));
  },
  getUuid: () => {
    return new Promise((rs, rj) => {
      let userDir = os.homedir();
      let uuidFilePath = path.resolve(userDir, "scanUuid.txt");
      if (fs.existsSync(uuidFilePath)) {
        fs.readFile(uuidFilePath, "utf8", (err: any, data: any) => {
          if (err) rj('"获取uuid文件异常！"');
          rs(data);
        });
      } else {
        const uuid = uuidv4();
        fs.writeFile(uuidFilePath, uuid, (err: any) => {
          if (err) {
            rj("uuid保存异常！");
          } else {
            rs(uuid);
          }
        });
      }
    });
  },
  watchScanProcess: () => {
    let num = 10;
    const watchStep = (rs: any, rj: any) => {
      isRunning("client.exe", (status: boolean) => {
        if (status) {
          rs(true);
        } else {
          if (num == 0) {
            rj();
            return;
          }
          num--;
          setTimeout(() => {
            watchStep(rs, rj);
          }, 1000);
        }
      });
    };
    return new Promise((rs, rj) => {
      watchStep(rs, rj);
    });
  },
});
