const { app, BrowserWindow, screen, session, ipcMain} = require('electron')
const path = require('path')

let mainWindow;
const createWindow = () => {
    // 获取主显示器的尺寸
    const primaryDisplay = screen.getPrimaryDisplay()
    const { width, height } = primaryDisplay.workAreaSize

    mainWindow = new BrowserWindow({
        width: width,
        height: height,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
            contextIsolation: true,
            nodeIntegration: true
        }
    })

    // 将窗口位置设置为(0,0)，确保它位于屏幕左上角
    mainWindow.setPosition(0, 0)

    mainWindow.loadFile(path.join(__dirname, '../dist/index.html'))

    // 添加 'close' 事件监听器
    mainWindow.on('close', (event) => {
        event.preventDefault(); // 阻止窗口立即关闭
        mainWindow.webContents.send('clear-token-cache');
    });
}

app.on('ready', () => {
    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.125:8014'
    session.defaultSession.webRequest.onBeforeRequest(filter, (details, callback) => {
        const val = details.url
        let newUrl = val.replace('file:///api', url);
        newUrl = newUrl.replace('file:///C:/api', url);
        newUrl = newUrl.replace('file:///D:/api', url);
        callback({ redirectURL: newUrl });
    });
});

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

    //下载文件
    ipcMain.on('download-file', async (event, url) => {
        if (!url) return
        const filePath = path.join(app.getPath('downloads'));
        const win = BrowserWindow.fromWebContents(event.sender);
        win.webContents.downloadURL(url, filePath);
    });

    // 监听渲染进程发来的缓存清理完成的消息
    ipcMain.on('token-cache-cleared', () => {
        setTimeout(() => {
            if (mainWindow && !mainWindow.isDestroyed()) {
                mainWindow.destroy();
            }
            app.quit();
        },500)
    });
})

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;
});
