import { Tray, Menu, app, BrowserWindow } from 'electron'
import { join } from 'path'
import icon from '../../resources/icon.png?asset'
import { getMainWindow, createWindow, createApiConfigWindow, createConfigWindow ,getDragWindow} from './window.js'
import { getStoreValue, setStoreValue, clearStore } from './store.js'
import { createDrageWindow, getDrageWindow } from './window.js'
import logger from './utils/logger'
import fs from 'fs'

let tray = null

import {checkForUpdates} from "./utils/updateUtils"

async function clearBrowserCache() {
  try {
    // 清除所有窗口的浏览器缓存
    const windows = BrowserWindow.getAllWindows()
    for (const window of windows) {
      const session = window.webContents.session
      await session.clearStorageData({
        storages: [
          'appcache',
          'cookies',
          'filesystem',
          'indexdb',
          'localstorage',
          'shadercache',
          'websql',
          'serviceworkers',
          'cachestorage'
        ]
      })
    }

    logger.info('浏览器缓存清除成功')
  } catch (error) {
    logger.error('清除浏览器缓存失败:', error)
  }
}

export function createTray() {
  // 创建托盘图标
  tray = new Tray(icon)

  // 设置托盘图标的提示文本
  tray.setToolTip('Dify Market Manager')

  // 创建右键菜单
  const contextMenu = Menu.buildFromTemplate([
    {
      label: '显示主窗口',
      click: () => {
        const mainWindow = getMainWindow()
        if (mainWindow) {
          mainWindow.show()
        } else {
          createWindow()
        }
      }
    },
    {
      label: '隐藏主窗口',
      click: () => {
        const mainWindow = getMainWindow()
        if (mainWindow) {
          mainWindow.hide()
        }
      }
    },
    { type: 'separator' },
    {
      label: '配置',
      submenu: [
        { type: 'separator' },
        {
          label: '配置客户端地址',
          click: () => {
            createConfigWindow()
          }
        }
      ]
    },
    { type: 'separator' },
    {
      label: '显示隐藏桌面悬浮',
      click: () => {
        const drageWindow = getDrageWindow()
        if (!drageWindow) {
          createDrageWindow()
        } else {
          if (drageWindow.isVisible()) {
            drageWindow.hide()
            setStoreValue('showDrageWindow', false)
          } else {
            drageWindow.show()
            setStoreValue('showDrageWindow', true)
          }
        }



      }
    },
    { type: 'separator' },
    {
      label: '检查更新',
      click: async (menuItem) => {
          checkForUpdates(menuItem,true)
      }
    },
    { type: 'separator' },
    {
      label: '清除缓存',
      click: async () => {
        await clearBrowserCache()

        // 删除配置文件
        try {
          const userDataPath = app.getPath('userData')
          const configPath = join(userDataPath, 'config.json')
          if (fs.existsSync(configPath)) {
            fs.unlinkSync(configPath)
            logger.info('配置文件删除成功')
          }
        } catch (error) {
          logger.error('删除配置文件失败:', error)
        }

        // 重新加载所有窗口
        const windows = BrowserWindow.getAllWindows()
        for (const window of windows) {
          window.reload()
        }
      }
    },
    { type: 'separator' },
    {
      label: '退出登录',
      click: async () => {
        await clearBrowserCache()
        // 重新加载主窗口
        const mainWindow = getMainWindow()
        if (mainWindow) {
          mainWindow.reload()
        }
        logger.info('用户已退出登录')
      }
    },
    { type: 'separator' },
    {
      label: '退出应用',
      click: () => {
        app.isQuiting = true
        // 确保所有窗口都被关闭
        BrowserWindow.getAllWindows().forEach(window => {
          window.destroy()
        })
        app.quit()
      }
    }
  ])

  // 设置托盘图标的右键菜单
  tray.setContextMenu(contextMenu)

  // 点击托盘图标时显示/隐藏主窗口
  tray.on('click', () => {
    const mainWindow = getMainWindow()
    if (mainWindow) {
      if (mainWindow.isVisible()) {
        mainWindow.hide()
      } else {
        mainWindow.show()
      }
    } else {
      createWindow()
    }
  })
}

export function destroyTray() {
  if (tray) {
    tray.destroy()
    tray = null
  }
}
