'use strict';

const path = require('path');
const fs = require('fs');
const { Controller } = require('ee-core');
const { spawn } = require('child_process');
const { liveShow, liveHide, setParams, capture, getParams,CMD } = require('../api/camera');
const { dialog } = require('electron'); // 引入 electron 的 dialog 模块

// 检查并读取配置文件
function readConfigFile(configPath) {
  try {
    // 检查文件是否存在
    if (!fs.existsSync(configPath)) {
      // 创建默认配置文件
      const defaultConfig = {
        digiCamControl: ''
      };
      fs.writeFileSync(configPath, JSON.stringify(defaultConfig, null, 2));
      return defaultConfig;
    }
    // 读取配置文件
    return JSON.parse(fs.readFileSync(configPath, 'utf8'));
  } catch (error) {
    console.error('读取配置文件时出错:', error);
    throw error;
  }
}

const configPath = path.join(__dirname, '..', 'config', 'app.config.json');
const config = readConfigFile(configPath);

async function checkCameraControlCmdExists() {
  try {
    // 获取 digiCamControl 文件夹路径
    const digiCamControlPath = config.digiCamControl;

    // 拼接 CameraControlCmd.exe 的完整路径
    const exePath = path.join(digiCamControlPath, 'CameraControl.exe');

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

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

      if (!canceled && filePaths.length > 0) {
        const selectedPath = filePaths[0];
        // 更新 app.config.json 中的 digiCamControl 值
        config.digiCamControl = selectedPath;
        fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
        return true; // 重新检查文件是否存在
      } else {
        console.error('用户未选择文件夹');
        return false;
      }
    }


    console.log('aaaa2')
    const res = await openCameraControlCmd();
    return res;
  } catch (error) {
    console.error('检查 CameraControlCmd.exe 是否存在时出错:', error);
    throw error;
  }
}


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

      // 拼接 CameraControlCmd.exe 的完整路径
      const exePath = path.join(digiCamControlPath, 'CameraControl.exe');

      // 检查文件是否存在
      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) {
        console.error('error CameraControlCmd.exe:', error);
        throw error;
      }

      console.log('CameraControlCmd.exe start');
    } catch (error) {
      console.error('无法找到或运行 CameraControlCmd.exe:', error);
      throw error;
    }
  })
}

class CameraController extends Controller {
  constructor(ctx) {
    super(ctx);
  }

  async connect() {
    const win = this.app.electron.mainWindow;
    try {
      win.setAlwaysOnTop(true); // 置顶
      console.log('aaaa')
       await checkCameraControlCmdExists()
      await  CMD('All_Minimize')
      win.setAlwaysOnTop(false); // 置顶

      const res = await getParams('iso')
      if(res  === '未将对象引用设置到对象的实例。'){
        return {
          status:-1,
          msg:"相机未连接，请链接相机。",
        }
      }
      return {
        status:2,
        msg:res,
      }
      return true;
    } catch (error) {
      win.setAlwaysOnTop(false); // 置顶
      return {
        status:-1,
        msg:"请安装digiCamControl软件，并打开digiCamControl软件的web服务，端口为5513",
      }
    }
  }

  /**
   * 启动预览
   */
  async liveShow() {
    try {
      await liveShow();
      await  CMD('All_Minimize')
      return true;
    } catch (error) {
      console.error('eeee启动直播失败:', error);
      throw error;
    }
  }

  /**
   * 结束预览
   */
  async liveHide() {
    try {
      await liveHide();
      return true;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 设置参数
   */
  async setParams(params) {
    try {
      console.log(params);
      await setParams(params);
      return true;
    } catch (error) {
      throw error;
    }
  }

  async takePictures() {
    try {
      await capture();
      return true;
    } catch (error) {
      throw error;
    }
  }

  // 示例：使用 fetchData 函数进行 HTTP 请求
  async fetchExampleData() {
    const options = {
      hostname: 'example.com',
      port: 443,
      path: '/api/data',
      method: 'GET'
    };

    try {
      const data = await fetchData(options);
      console.log('Fetched data:', data);
      return data;
    } catch (error) {
      console.error('Fetch data failed:', error);
      throw error;
    }
  }
}

CameraController.toString = () => '[class CameraController]';
module.exports = CameraController;
