import { BrowserWindow } from "electron";

let win: BrowserWindow;

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

export function log(...data: any[]): void {
  if (win) {
    exec(() => win.webContents.executeJavaScript("console.log('%cELECTRON', 'color: #800', '" + dataToText(...data) + "');"));
  }
  else {
    console.log(...data);
  }
}

export function error(...data: any[]): void {
  if (win) {
    exec(() => win.webContents.executeJavaScript("console.error('%cELECTRON', 'color: #800', '" + dataToText(...data) + "');"));
  }
  else {
    console.error(...data);
  }
}

function dataToText(...data: any[]): string {
  let text = "";
  for (const item of data) {
    const str = item === undefined ? "undefined" :
      (item === null ? "null" :
        (item instanceof Error ? item.toString() + " " + item.stack : item.toString()));
    text += (text.length > 0 ? " " : "") + str;
  }
  const regExp1 = /\\/g;
  const regExp2 = /'/g;
  const regExp3 = /\s/g;
  return text.replace(regExp1, "\\\\").replace(regExp2, "\\'").replace(regExp3, " ");
}

function exec(func: () => void): void {
  try {
    func();
  }
  catch (e) {
    try {
      win.webContents.executeJavaScript("console.error('%cELECTRON', 'color: #800', '" + dataToText("Web console error:", e) + "');");
    }
    catch {
      console.error("Web console error:", e);
    }
  }
}
