import { join } from 'path'
import {
    BrowserWindow,
    Menu,
    app,
    ipcMain,
    screen,
    session,
    shell,
} from 'electron'
import { electronApp, is } from '@electron-toolkit/utils'

let mainWindow

// 菜单设置
const createMenu = () => {
    const menu = Menu.buildFromTemplate([
        {
            label: app.name,
            submenu: [
                { type: 'separator' },
                { label: '刷新', role: 'reload' },
                { label: '强制刷新', role: 'forceReload' },
                { type: 'separator' },
                {
                    label: '调试',
                    click: () => {
                        if (mainWindow && !mainWindow.isDestroyed()) {
                            mainWindow.webContents.openDevTools()
                        }
                    },
                },
                { type: 'separator' },
                { label: '退出' + app.name, role: 'quit' },
            ],
        },
        {
            label: '编辑',
            submenu: [
                { label: '撤销', role: 'undo' },
                { label: '重做', role: 'redo' },
                { type: 'separator' },
                { label: '剪切', role: 'cut' },
                { label: '复制', role: 'copy' },
                { label: '粘贴', role: 'paste' },
                { label: '删除', role: 'delete' },
                { type: 'separator' },
                { label: '全选', role: 'selectAll' },
            ],
        },
    ])
    Menu.setApplicationMenu(menu)
}

function createWindow() {
    const primaryDisplay = screen.getPrimaryDisplay()
    const { width, height } = primaryDisplay.workAreaSize

    mainWindow = new BrowserWindow({
        width: width,
        height: height,
        center: true,
        show: false,
        autoHideMenuBar: false,
        webPreferences: {
            preload: join(__dirname, '../preload/index.js'),
            sandbox: false,
            webviewTag: true,
            nodeIntegration: true,
            contextIsolation: true,
            webSecurity: true,
        },
    })

    mainWindow.on('ready-to-show', () => {
        mainWindow.show()
    })

    mainWindow.webContents.setWindowOpenHandler((details) => {
        shell.openExternal(details.url)
        return { action: 'deny' }
    })

    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
        mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
    } else {
        mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
    }

    mainWindow.on('close', (event) => {
        if (mainWindow && !mainWindow.isDestroyed()) {
            event.preventDefault()
            mainWindow.webContents.send('clear-token-cache')
        }
    })
    // 添加 CSP 配置
    mainWindow.webContents.session.webRequest.onHeadersReceived((details, callback) => {
        callback({
            responseHeaders: {
                ...details.responseHeaders,
                'Content-Security-Policy': [
                    'default-src \'self\' \'unsafe-inline\' \'unsafe-eval\' data: blob:; '
                    + 'script-src \'self\' \'unsafe-inline\' \'unsafe-eval\'; '
                    + 'style-src \'self\' \'unsafe-inline\'; '
                    + 'img-src \'self\' data: blob: https:; '
                    + 'connect-src \'self\' https: ws: wss:; '
                    + 'font-src \'self\' data:;',
                ],
            },
        })
    })
}

function setupWebRequestFilter() {
    const filter = {
        urls: ['file:///C:/api/*', 'file:///api/*', 'file:///D:/api/*'],
    }
    //const url = 'http://127.0.0.1:8014'
        const url = 'http://192.168.0.109:8014'
    // const url = 'http://219.151.181.73:8014'
            // const url = 'http://192.168.0.21:8014'
    session.defaultSession.webRequest.onBeforeRequest(
        filter,
        (details, callback) => {
            const val = details.url
            let newUrl = val.replace(/^file:\/\/\/(?:C:\/)?(?:D:\/)?api/, url)
            callback({ redirectURL: newUrl })
        },
    )
}

function initApp() {
    createWindow()
    createMenu()
    electronApp.setAppUserModelId('com.local.analysis.app')

    if (!app.requestSingleInstanceLock()) {
        app.quit()
    } else {
        app.on('second-instance', (event, argv) => {
            if (process.platform !== 'darwin') {
                if (!mainWindow) {
                    createWindow()
                    return
                }
                if (mainWindow.isMinimized()) mainWindow.restore()
                mainWindow.show()
                mainWindow.focus()
            }
        })
    }

    ipcMain.handle('download-file', async (event, url) => {
        if (!url) return
        const filePath = join(app.getPath('downloads'))
        const win = BrowserWindow.fromWebContents(event.sender)
        if (win && !win.isDestroyed()) {
            win.webContents.downloadURL(url, filePath)
        }
    })

    ipcMain.handle('token-cache-cleared', () => {
        setTimeout(() => {
            if (mainWindow && !mainWindow.isDestroyed()) {
                mainWindow.destroy()
            }
            app.quit()
        }, 500)
    })

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

app.on('ready', () => {
    setupWebRequestFilter()
    initApp()
})

app.on('before-quit', (event) => {
    if (mainWindow && !mainWindow.isDestroyed()) {
        event.preventDefault()
        mainWindow.webContents.send('clear-token-cache')
    }
})

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit()
})

app.on('will-quit', () => {
    mainWindow = null
})
