/**
 * This module is responsible on handling all the inter process communications
 * between the frontend to the electron backend.
 */

import { app, ipcMain } from 'electron';
import * as os from 'os';
import { environment } from '../../environments/environment';
import {
    DEBUG_TRACE_EVENT_CHANNEL,
    isRendererApiTraceEnabled,
    trace,
} from '../services/debug-trace';

export default class ElectronEvents {
  static bootstrapElectronEvents(): Electron.IpcMain {
    return ipcMain;
  }
}

// Retrieve app version
ipcMain.handle('get-app-version', (event) => {
  console.log(`Fetching application version... [v${environment.version}]`);

  return environment.version;
});

// Handle App termination
ipcMain.on('quit', (event, code) => {
  app.exit(code);
});

ipcMain.on(DEBUG_TRACE_EVENT_CHANNEL, (event, payload) => {
  if (!isRendererApiTraceEnabled()) {
    return;
  }

  trace('renderer-api', 'event', {
    payload,
    senderId: event.sender.id,
    url: event.sender.getURL(),
  });
});

// Get local IP addresses for remote control URL display
ipcMain.handle('get-local-ip-addresses', () => {
  const interfaces = os.networkInterfaces();
  const addresses: string[] = [];

  for (const name of Object.keys(interfaces)) {
    for (const iface of interfaces[name] || []) {
      // Skip internal (loopback) and non-IPv4 addresses
      if (iface.family === 'IPv4' && !iface.internal) {
        addresses.push(iface.address);
      }
    }
  }

  return addresses;
});
