import path from 'node:path';
import { is, optimizer } from '@electron-toolkit/utils';
import { BrowserWindow, app, ipcMain, shell } from 'electron';
import { RelayManager } from './relayManager';

const relay = new RelayManager();

ipcMain.handle('relay:start', (_, ...args: string[]) => {
  if (!args[0]) throw new Error('No encryption key provided');
  const encryptionKey = args[0];
  return relay.start(encryptionKey);
});

ipcMain.handle('relay:stop', () => {
  return relay.stop();
});

ipcMain.handle('relay:reset', () => {
  return relay.reset();
});

ipcMain.handle('relay:status', () => {
  return {
    running: relay.isRunning,
    pid: relay.pid,
    logs: relay.getLogs(),
  };
});

function createWindow(): void {
  const mainWindow = new BrowserWindow({
    width: 1366,
    height: 768,
    show: false,
    minWidth: 1366,
    minHeight: 768,
    autoHideMenuBar: true,
    webPreferences: {
      preload: path.join(__dirname, '../preload/preload.mjs'),
      sandbox: false,
    },
  });

  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(path.join(__dirname, '../renderer/index.html'));
}

app.whenReady().then(() => {
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window);
  });

  createWindow();
});

app.on('window-all-closed', () => {
  app.quit();
});
