const axios = require('axios');
const http = require('http');
const { net } = require('electron');
const { post } = require('./request')
const { windowManager } = require('node-window-manager');
//
const baseURL = 'http://localhost:5513/';
// 创建 Axios 实例
const service = axios.create({
  baseURL:baseURL,
  timeout: 60000,
});


// 封装 GET 方法
function get(config = { url: '' }) {
  return service.get(config.url, {
    insecureHTTPParser: true,
    timeout: config.timeout || 60000,
  });
}


async function fetchExampleData(url) {
  return new Promise((resolve, reject) => {
    const request = net.request({
      method: 'GET',
      url: baseURL+url
    });

    request.on('response', (response) => {
      let data = '';
      response.on('data', (chunk) => {
        data += chunk;
      });
      response.on('end', () => {
        try {
          resolve(data);
        } catch (error) {
          console.error('Error parsing data:', error);
          reject(error);
        }
      });
    });

    request.on('error', (error) => {
      console.error('Request error:', error);
      reject(error);
    });

    request.end();
  });
}


const socket = require('../utils/socket')
const pySocket = new socket()
const { readConfigFile } = require('../utils/config');


module.exports = {
  async liveShow(){
    if(readConfigFile().controlType === 'digiCamControl'){
      return get({
        url: '?CMD=LiveViewWnd_Show'
      })
    }else{

      await pySocket.sendMessage(JSON.stringify({
        type: 'smart_shooter_enable_preview',
        data:{
          value:true
        }
      }))
      return  new Promise(async (resolve, reject) => {
        pySocket.onSocketMessage('smart_shooter_enable_preview',(message)=>{

          resolve(message)
        })
      })
    }
  },
  async liveHide(){
    if(readConfigFile().controlType === 'digiCamControl'){
      return get({
        url: '?CMD=LiveViewWnd_Hide'
      })
    }else{

      await pySocket.sendMessage(JSON.stringify({
        type: 'smart_shooter_enable_preview',
        data:{
          value:false
        }
      }))
      return  new Promise(async (resolve, reject) => {
        pySocket.onSocketMessage('smart_shooter_enable_preview',(message)=>{

          resolve(message)
        })
      })
    }
  },
  captureLive(){
    return get({
      url: '?CMD=LiveView_Capture'
    })
  },
  capture(){
    return get({
      url: '?CMD=Capture'
    })
  },

  CMD(cmd){
    return get({
      url: '?CMD='+cmd
    })
  },

  getParams(params){
    return  fetchExampleData(`?slc=get&param1=${params}`)
  },
  setParams(params){

    return get({
      url: `?slc=set&param1=${params.key}&param2=${params.value}`
    })
  },
  closeOtherWindow(){
    return post({
      url: '/close_other_window',
    })
  },
  async minimizeSmartShooter(){
    try {
      // 获取所有窗口
      const windows = windowManager.getWindows();
      
      // 查找SmartShooter窗口
      const smartShooterWindow = windows.find(window => {
        const title = window.getTitle().toLowerCase();
        return title.includes('smartshooter') || title.includes('smart shooter');
      });
      
      if (smartShooterWindow) {
        // 最小化窗口
        smartShooterWindow.minimize();
        console.log('SmartShooter窗口已最小化');
        return { success: true, message: 'SmartShooter窗口已最小化' };
      } else {
        console.log('未找到SmartShooter窗口');
        return { success: false, message: '未找到SmartShooter窗口' };
      }
    } catch (error) {
      console.error('最小化SmartShooter失败:', error);
      return { success: false, message: '最小化失败: ' + error.message };
    }
  },
  async checkCamera(){
    if(readConfigFile().controlType === 'digiCamControl'){
      return  fetchExampleData(`?slc=get&param1=iso`)
    }else {

      await pySocket.sendMessage(JSON.stringify({
        type: 'smart_shooter_getinfo',
        data:{}
      }))
     return  new Promise(async (resolve, reject) => {
        pySocket.onSocketMessage('smart_shooter_getinfo',(message)=>{
          resolve(message)
        })
      })
    }
  }
}


/*
*
* 设置   iso
* 光圈  aperture
* 拍摄模式  mode
* 快门速度  shutterSpeed
* 白平衡    whitebalance
* 曝光补偿  ExposureCompensation
* 对焦模式 focusmode
*
*folder 文件夹
曝光度：exposure
压缩：compression
测光点：metering
* */
