import { Tray, Menu, BrowserWindow, app, nativeImage } from 'electron'
import * as path from 'path'
import * as fs from 'fs'

let tray: Tray | null = null

export function createTray(win: BrowserWindow): void {
  const iconPath = path.join(__dirname, '../../src/assets/icon.png')

  let icon: Electron.NativeImage
  if (fs.existsSync(iconPath)) {
    icon = nativeImage.createFromPath(iconPath)
  } else {
    icon = nativeImage.createEmpty()
  }

  try {
    tray = new Tray(icon)
  } catch {
    return
  }

  const contextMenu = Menu.buildFromTemplate([
    {
      label: '显示主面板',
      click: () => {
        win.show()
        win.focus()
      }
    },
    { type: 'separator' },
    {
      label: '退出',
      click: () => {
        app.quit()
      }
    }
  ])

  tray.setToolTip('AI 阅卷助手')
  tray.setContextMenu(contextMenu)

  tray.on('click', () => {
    win.show()
    win.focus()
  })
}
