import type { BrowserWindow } from 'electron'
import { app, ipcMain } from 'electron'
import type ElectronStore from 'electron-store'
import type { SettingStore } from '/#/store'

export async function useHandler(win: BrowserWindow, store: ElectronStore<SettingStore>) {
    // ==================== ipc handle ===================
    ipcMain.handle('window:action', (_, action: string) => {
        switch (action) {
            // 关闭程序
            case 'close':
                win.close()
                app.quit()
                break
            // 重新加载
            case 'reload':
                win.reload()
                break
            // 打开 F12
            case 'debug':
                win.webContents?.toggleDevTools()
                break
            // 最大化/还原
            case 'max':
                win.isMaximized() ? win.restore() : win.maximize()
                break
            // 最小化
            case 'min':
                win.minimize()
                break
            // 置顶/取消置顶
            case 'top':
                win.setAlwaysOnTop(!win.isAlwaysOnTop())
                break
            default:
                console.warn('[window:action] unknow', action)
                break
        }
    })

    win.on('maximize', () => {
        win.webContents.send('window:action', 'max')
    })

    win.on('unmaximize', () => {
        win.webContents.send('window:action', 'unmax')
    })

    // 设置窗口是否总在最前
    if (store.get('system.alwaysOnTop')) {
        win.setAlwaysOnTop(true)
    }
}
