// electron/utils/readConfig.js

const path = require('path');
const fs = require('fs');
const Log = require('ee-core/log');
const { spawn } = require('child_process');
const { liveShow, liveHide, setParams, capture, getParams,CMD,captureLive,closeOtherWindow,minimizeSmartShooter } = require('../api/camera');

const { dialog } = require('electron'); // 引入 electron 的 dialog 模块
const { windowManager } = require('node-window-manager');
const CoreWindow = require("ee-core/electron/window");


const { readConfigFile, writeConfigFile } = require('../utils/config');

const exe = {
  "digiCamControl":"CameraControl.exe",
  "SmartShooter":"SmartShooter5.exe",
}


function getExePath () {
  let exePath =  ""
  if(readConfigFile().controlType === 'digiCamControl'){
    exePath =  path.join( readConfigFile().controlPath || readConfigFile().digiCamControlPath, exe["digiCamControl"]);
  }else if(readConfigFile().controlType === 'SmartShooter'){
    exePath =  path.join( readConfigFile().controlPath || readConfigFile().SmartShooterPath,  exe["SmartShooter"]);
  }

  console.log('ex============ePath');
  console.log(exePath);
  return exePath
}




async function checkCameraControlCmdExists() {
  try {

    // 拼接 CameraControlCmd.exe 的完整路径

    let exePath = getExePath()
    // 检查文件是否存在
    const exists = await fs.promises.access(exePath, fs.constants.F_OK)
        .then(() => true)
        .catch(() => false);

    if (!exists) {
      // 弹出文件夹选择对话框
      const { canceled, filePaths } = await dialog.showOpenDialog({
        title: '选择 相机控制安装软件 文件夹',
        properties: ['openDirectory']
      });

      if (!canceled && filePaths.length > 0) {
        const selectedPath = filePaths[0];

        // Check if SmartShooter5.exe exists in the selected directory
        const hasExe = path.join(selectedPath, exe["SmartShooter"]);

        if (fs.existsSync(hasExe)) {
          writeConfigFile("controlType","SmartShooter")
        }else{
          writeConfigFile("controlType","digiCamControl")
        }
        writeConfigFile("controlPath",selectedPath)
      } else {
        console.error('用户未选择文件夹');
        return {
          status:-1,
          msg:"无法找到 CameraControlCmd.exe 或者  SmartShooter5.exe",
        }
      }
    }
    const res = await openCameraControlCmd();
    
    // 如果是SmartShooter，启动后最小化窗口
    if(readConfigFile().controlType === 'SmartShooter'){
      // 等待软件启动完成
      setTimeout(async () => {
        try {
          await minimizeSmartShooter();
        } catch (error) {
          console.log('最小化SmartShooter失败:', error);
        }
      }, 3000); // 等待3秒让软件完全启动
    }
    
    return res;
  } catch (error) {
    Log.error('检查 第三方相机控制器 是否存在时出错:', error);
    throw error;
  }
}


async function openCameraControlCmd(digiCamControlPath) {
  return  new Promise(async (resolve, reject) => {
    try {
      // 获取 digiCamControl 文件夹路径

      // 拼接 CameraControlCmd.exe 的完整路径
      let exePath = getExePath()

      // 检查文件是否存在
      await fs.promises.access(exePath, fs.constants.F_OK);
      try {

        const child = spawn(exePath);

        child.stdout.on('data', (data) => {
          resolve(true)
        });

        child.on('close', (code) => {
          if (code === 0) {
            reject(false)
          }
        });



      } catch (error) {
        Log.error('error 第三方相机控制器:', error);
        throw error;
      }

    } catch (error) {
      Log.error('无法找到或运行 第三方相机控制器:', error);
      throw error;
    }
  })
}

async function closeCameraControlTips() {
  try {
    await  closeOtherWindow()

  }catch (e) {
    console.log(e)
  }


}

module.exports = {
  checkCameraControlCmdExists,
  closeCameraControlTips,
  minimizeSmartShooter
};
