import { screen, ipcMain, BrowserWindow, Display } from "electron";
import type Electron from "electron";
import { MessageId } from "./types";
import Window from "./Window";
import {__} from "./i18n";

export type DisplayInfo = {
  id: number;
  name: string;
  isPrimary: boolean;
  index: number;
  windowCount: number;
  width: number;
  height: number;
};

let mainWindow: BrowserWindow;

export function init(mainWin: BrowserWindow): void {
  mainWindow = mainWin;

  screen.on("display-added", publishDisplaysChanged);
  screen.on("display-removed", publishDisplaysChanged);
  screen.on("display-metrics-changed", publishDisplaysChanged);

  ipcMain.on(MessageId.GetDisplays, (event) => {
    const primaryId = screen.getPrimaryDisplay().id;
    const displays: DisplayInfo[] = screen.getAllDisplays().map(({ id, size: { width, height }, internal }, index) => ({
      id,
      name: (index + 1) + ": " + (id === primaryId ? __("Primary") : (internal ? __("Internal") : __("External"))) + ` ${width} x ${height}`,
      isPrimary: id === primaryId,
      index,
      windowCount: Window.windows.filter(w => w.displayId === id).length,
      width,
      height
    }));
    event.reply(MessageId.GetDisplaysReply, displays);
  });
}

export function getDisplay(displayId?: number, rect?: Electron.Rectangle): Display {
  let display = screen.getAllDisplays().find(d => d.id === displayId);
  if (!display && rect) {
    display = screen.getDisplayMatching(rect);
  }
  return display ?? screen.getPrimaryDisplay();
}

function publishDisplaysChanged(): void {
  if (mainWindow) {
    mainWindow.webContents.send(MessageId.DisplaysChanged);
  }
}
