import { ipcMain, BrowserWindow } from 'electron';
import { join } from 'path';

// export
let childrenWindows: BrowserWindow[] = [];
async function handleStartWinProcess(
  event: Electron.IpcMainEvent,
  processCount: number,
  loadPageUrl: string
) {
  if (childrenWindows.length) {
    childrenWindows.forEach((win) => win && win.close());
    childrenWindows = [] as BrowserWindow[];
  }

  const parentWindow = BrowserWindow.getFocusedWindow();
  if (!parentWindow) return;

  const createWins = [] as Promise<BrowserWindow>[];
  for (let i = 0; i < processCount; i++) {
    createWins.push(buildChildWindow(parentWindow, loadPageUrl));
  }
  childrenWindows = await Promise.all(createWins);
}

async function buildChildWindow(
  parentWindow: BrowserWindow,
  loadPageUrl: string
) {
  const childWin = new BrowserWindow({
    width: 400,
    height: 400,
    show: false,
    parent: parentWindow,
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      webSecurity: false,
    },
  });

  const pageUrl = `${loadPageUrl}&winId=${childWin.id}`;
  if (process.env.ELECTRON_RENDERER_URL) {
    // Load the url of the dev server if in development mode
    await childWin.loadURL(process.env.ELECTRON_RENDERER_URL + pageUrl);
    // childWin.webContents.openDevTools();
  } else {
    // Load the index.html when not in development
    await childWin.loadFile(join(__dirname, '../renderer/index.html'), {
      hash: pageUrl,
    });
  }
  return childWin;
}

function handleStopWinProcess() {
  if (!childrenWindows.length) return;
  childrenWindows.forEach((cwin) => {
    cwin.webContents.send('stop-running');
  });
}

function handleCloseProcessWindow(event: Electron.IpcMainEvent, winId: number) {
  if (!childrenWindows.length) return;

  const pos = childrenWindows.findIndex((item) => item.id === winId);
  if (pos !== -1) {
    childrenWindows[pos].close();
    childrenWindows.splice(pos, 1);
  }
}

export default function useWinProcess() {
  ipcMain.on('start-win-process', handleStartWinProcess);
  ipcMain.on('stop-win-process', handleStopWinProcess);
  ipcMain.on('close-process-window', handleCloseProcessWindow);
}
