import { app, BrowserWindow, ipcMain } from 'electron';
import path from 'node:path';
import started from 'electron-squirrel-startup';

// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (started) {
  app.quit();
}

// 处理设置Cookie的IPC请求
ipcMain.handle('set-cookie', async (event, cookie) => {
  try {
    await event.sender.session.cookies.set(cookie);
    return true;
  } catch (error) {
    console.error('设置Cookie失败:', error);
    return false;
  }
});

const createWindow = () => {
  // Create the browser window.
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      contextIsolation: true, // 启用上下文隔离。
      nodeIntegration: false, // 禁用 Node.js 集成，提高安全性。
      preload: path.join(__dirname, 'preload.js'), // 预加载脚本
      webviewTag: true, // 启用webview标签
      webSecurity: false,
      allowRunningInsecureContent: true,
      sandbox: false
    },
  });

  // 设置session
  win.webContents.session.setPermissionRequestHandler((webContents, permission, callback) => {
    callback(true);
  });

  win.setMenuBarVisibility(false); // 隐藏菜单栏
  win.setAutoHideMenuBar(true); // 自动隐藏菜单栏
  win.setMenu(null); // 隐藏菜单栏

  // and load the index.html of the app.
  if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
    win.loadURL(`${MAIN_WINDOW_VITE_DEV_SERVER_URL}/login.html`);
  } else {
    win.loadFile(path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/login.html`));
  }

  // Open the DevTools.
  win.webContents.openDevTools();
};

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);

// 在非 macOS 平台上，关闭所有窗口时退出应用
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

// 在 macOS 平台上，点击 dock 图标时重新创建窗口
app.on('activate', () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});