import { app, shell, BrowserWindow, ipcMain, Menu, session, screen, dialog } from 'electron'
import { electronApp, optimizer } from '@electron-toolkit/utils'
import Store from 'electron-store'
import { createWindow, createDrageWindow, unregisterAllShortcuts } from './window.js'
import { setupIPC } from './ipc.js'
import { createTray, destroyTray } from './tray.js'
import { getStoreValue } from './store.js'
import XEUtils from 'xe-utils'

import logger from './utils/logger'

import AutoLaunch from 'auto-launch'

import WebSocketClient from './utils/WebSocketClient';

let wsClient=null

wsClient=new WebSocketClient({
  autoReconnect: true,
  autoReconnectAttempts: 9999,
  autoReconnectInterval: 5000,
  timeout: 30000,
})

wsClient.on('open', () => {
  logger.info('WebSocket连接已打开')
});


var minecraftAutoLauncher = new AutoLaunch({
  name: '百千万AI智能体共创平台',
  path: app.getPath('exe')
});

app.commandLine.appendSwitch('allow-insecure-localhost'); // 允许本地回环地址使用不安全连接
app.commandLine.appendSwitch('ignore-certificate-errors'); // 忽略证书错误（开发时可用）

const h5_client_url=getStoreValue("h5_client_url")
if(!XEUtils.isEmpty(h5_client_url)){
  logger.info("=======================h5_client_url 非空，设置 unsafely-treat-insecure-origin-as-secure的值为:"+h5_client_url)
  app.commandLine.appendSwitch('unsafely-treat-insecure-origin-as-secure', h5_client_url);
}

let difySite=getStoreValue("difySite")
if(!XEUtils.isEmpty(difySite)){
  difySite = XEUtils.parseUrl(difySite)
  logger.info("=======================h5_client_url 非空，设置 unsafely-treat-insecure-origin-as-secure的值为:"+h5_client_url+","+difySite.origin)
  app.commandLine.appendSwitch('unsafely-treat-insecure-origin-as-secure', h5_client_url+","+difySite.origin);
}


// 设置控制台编码为 UTF-8
logger.info(`当前运行平台: ${process.platform}`)
if (process.platform === 'win32') {
  logger.info('Windows 系统，设置控制台编码为 UTF-8')
  require('child_process').execSync('chcp 65001', { stdio: 'ignore' })
} else {
  logger.info('非 Windows 系统，使用默认编码')
}

logger.info('%cRed text. %cGreen text', 'color: red', 'color: green')

const store = new Store()

app.commandLine.appendSwitch('disable-features', 'OutOfBlinkCors')
app.commandLine.appendSwitch('ignore-certificate-errors')

app.disableHardwareAcceleration()

logger.info(app.getPath('userData'))



// 检查是否为第一个实例
const gotTheLock = app.requestSingleInstanceLock()

if (!gotTheLock) {
  // 如果不是第一个实例，尝试激活第一个实例的窗口
  const windows = BrowserWindow.getAllWindows()
  if (windows.length > 0) {
    const mainWindow = windows[0]
    if (mainWindow.isMinimized()) {
      mainWindow.restore()
    }
    mainWindow.show()
    mainWindow.focus()
  }
  app.quit() // 退出当前实例
} else {
  // 这是第一个实例

  // 监听第二个实例的启动
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    // 当运行第二个实例时，将显示第一个实例的窗口
    const windows = BrowserWindow.getAllWindows()
    if (windows.length > 0) {
      const mainWindow = windows[0]
      if (mainWindow.isMinimized()) {
        mainWindow.restore()
      }
      mainWindow.show()
      mainWindow.focus()
    }
  })

  app.whenReady().then(() => {

    // 获取默认会话并全局设置允许第三方 Cookie
    const defaultSession = session.defaultSession;

    // 设置 Cookie 策略以允许第三方 Cookie
    defaultSession.setPermissionRequestHandler((webContents, permission, callback) => {
      callback(true);
    });

    electronApp.setAppUserModelId('com.electron')

    app.on('browser-window-created', (_, window) => {
      optimizer.watchWindowShortcuts(window)
    })




    // 根据存储的状态决定是否创建悬浮窗口
    if (getStoreValue('showDrageWindow')) {
       createDrageWindow()
    }


    createWindow()


    createTray()
    setupIPC()


    minecraftAutoLauncher.isEnabled()
      .then(function(isEnabled){
        if(isEnabled){
          return;
        }
        minecraftAutoLauncher.enable();
      })
      .catch(function(err){
        logger.info(err)
      });



    app.on('activate', function () {
      if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
  })

  // 修改窗口关闭行为
  app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
      if (!app.isQuiting) {
        // 如果不是主动退出，则隐藏所有窗口
        BrowserWindow.getAllWindows().forEach(window => {
          window.hide()
        })
      } else {
        // 如果是主动退出，则销毁托盘并退出应用
        destroyTray()
        app.quit()
      }
    }
  })

  // 在应用退出时注销所有快捷键
  app.on('will-quit', () => {
    unregisterAllShortcuts()
  })
}
