"use strict";
const electron = require("electron");
const path = require("path");
const child_process = require("child_process");
const is = {
  dev: !electron.app.isPackaged
};
const platform = {
  isWindows: process.platform === "win32",
  isMacOS: process.platform === "darwin",
  isLinux: process.platform === "linux"
};
const electronApp = {
  setAppUserModelId(id) {
    if (platform.isWindows)
      electron.app.setAppUserModelId(is.dev ? process.execPath : id);
  },
  setAutoLaunch(auto) {
    if (platform.isLinux)
      return false;
    const isOpenAtLogin = () => {
      return electron.app.getLoginItemSettings().openAtLogin;
    };
    if (isOpenAtLogin() !== auto) {
      electron.app.setLoginItemSettings({
        openAtLogin: auto,
        path: process.execPath
      });
      return isOpenAtLogin() === auto;
    } else {
      return true;
    }
  },
  skipProxy() {
    return electron.session.defaultSession.setProxy({ mode: "direct" });
  }
};
const optimizer = {
  watchWindowShortcuts(window, shortcutOptions) {
    if (!window)
      return;
    const { webContents } = window;
    const { escToCloseWindow = false, zoom = false } = shortcutOptions || {};
    webContents.on("before-input-event", (event, input) => {
      if (input.type === "keyDown") {
        if (!is.dev) {
          if (input.code === "KeyR" && (input.control || input.meta))
            event.preventDefault();
        } else {
          if (input.code === "F12") {
            if (webContents.isDevToolsOpened()) {
              webContents.closeDevTools();
            } else {
              webContents.openDevTools({ mode: "undocked" });
              console.log("Open dev tool...");
            }
          }
        }
        if (escToCloseWindow) {
          if (input.code === "Escape" && input.key !== "Process") {
            window.close();
            event.preventDefault();
          }
        }
        if (!zoom) {
          if (input.code === "Minus" && (input.control || input.meta))
            event.preventDefault();
          if (input.code === "Equal" && input.shift && (input.control || input.meta))
            event.preventDefault();
        }
      }
    });
  },
  registerFramelessWindowIpc() {
    electron.ipcMain.on("win:invoke", (event, action) => {
      const win = electron.BrowserWindow.fromWebContents(event.sender);
      if (win) {
        if (action === "show") {
          win.show();
        } else if (action === "showInactive") {
          win.showInactive();
        } else if (action === "min") {
          win.minimize();
        } else if (action === "max") {
          const isMaximized = win.isMaximized();
          if (isMaximized) {
            win.unmaximize();
          } else {
            win.maximize();
          }
        } else if (action === "close") {
          win.close();
        }
      }
    });
  }
};
let child;
async function RunCommand(event, config_json, openOutputFolder) {
  let resourceUrl;
  config_json = Buffer.from(config_json, "utf8").toString("base64");
  if (!CheckPipPackage()) {
    if (process.env.NODE_ENV === "development") {
      resourceUrl = path.join(electron.app.getAppPath(), "/resources/Final2x-core/Final2x-core");
    } else {
      resourceUrl = path.join(electron.app.getAppPath(), "/resources/Final2x-core/Final2x-core");
    }
  } else {
    resourceUrl = "Final2x-core";
  }
  let command = `"${resourceUrl}" -b ${config_json}`;
  if (!openOutputFolder) {
    command += " -n";
  }
  console.log(command);
  child = child_process.spawn(command, { shell: true });
  child.stdout.on("data", (data) => {
    event.sender.send("command-stdout", data.toString());
  });
  child.stderr.on("data", (data) => {
    event.sender.send("command-stderr", data.toString());
  });
  child.on("close", (code) => {
    event.sender.send("command-close-code", code);
  });
}
async function KillCommand() {
  if (child) {
    child.kill();
  }
}
function CheckPipPackage() {
  const command = `Final2x-core -h`;
  const result = child_process.spawnSync(command, { shell: true, encoding: "utf-8" });
  return result.status === 0;
}
function openDirectory(event, p) {
  electron.dialog.showOpenDialog({
    properties: p
  }).then((result) => {
    console.log(result);
    event.sender.send("selectedItem", result.filePaths);
  }).catch((err) => {
    console.log(err);
  });
}
const icon = path.join(__dirname, "../../resources/icon.png");
const trayIcon = path.join(__dirname, "../../resources/tray.png");
function createWindow() {
  const mainWindow = new electron.BrowserWindow({
    width: 670,
    height: 470,
    maxWidth: 870,
    minWidth: 670,
    maxHeight: 670,
    minHeight: 470,
    frame: false,
    show: false,
    autoHideMenuBar: true,
    icon: electron.nativeImage.createFromPath(icon),
    webPreferences: {
      preload: path.join(__dirname, "../preload/index.js"),
      sandbox: false
    }
  });
  if (process.platform === "darwin") {
    electron.app.dock.setIcon(electron.nativeImage.createFromPath(icon));
  }
  electron.ipcMain.on("execute-command", RunCommand);
  electron.ipcMain.on("kill-command", KillCommand);
  electron.ipcMain.on("open-directory-dialog", openDirectory);
  electron.ipcMain.on("minimize", () => {
    mainWindow.minimize();
  });
  electron.ipcMain.on("maximize", () => {
    if (mainWindow.isMaximized()) {
      mainWindow.restore();
    } else {
      mainWindow.maximize();
    }
  });
  electron.ipcMain.on("close", () => {
    if (process.platform !== "darwin") {
      electron.app.quit();
    } else {
      electron.app.hide();
    }
  });
  mainWindow.on("ready-to-show", () => {
    mainWindow.show();
  });
  mainWindow.webContents.setWindowOpenHandler((details) => {
    electron.shell.openExternal(details.url);
    return { action: "deny" };
  });
  if (is.dev && process.env["ELECTRON_RENDERER_URL"]) {
    mainWindow.loadURL(process.env["ELECTRON_RENDERER_URL"]);
    mainWindow.webContents.openDevTools();
  } else {
    mainWindow.loadFile(path.join(__dirname, "../renderer/index.html"));
  }
}
let tray;
function setTray() {
  const Image = electron.nativeImage.createFromPath(trayIcon);
  Image.setTemplateImage(true);
  tray = new electron.Tray(Image);
  const contextMenu = electron.Menu.buildFromTemplate([
    {
      label: "Open",
      click: () => {
        if (electron.BrowserWindow.getAllWindows().length === 0) {
          createWindow();
        } else {
          electron.BrowserWindow.getAllWindows()[0].show();
        }
      }
    },
    {
      label: "Exit",
      click: () => {
        electron.app.quit();
      }
    }
  ]);
  tray.setToolTip("Final2x");
  tray.setContextMenu(contextMenu);
}
electron.app.whenReady().then(() => {
  electronApp.setAppUserModelId("com.electron");
  electron.app.on("browser-window-created", (_, window) => {
    optimizer.watchWindowShortcuts(window);
  });
  setTray();
  createWindow();
  electron.app.on("activate", function() {
    if (electron.BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});
electron.app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    electron.app.quit();
  }
});
