import path from "path";
import fs from "fs";
import { app, BrowserWindow, Menu, screen, dialog, ipcMain } from "electron";
import installExtension, { VUEJS3_DEVTOOLS } from "electron-devtools-installer";

import { exec } from "child_process";
import process from "process";

const isDev = process.env.NODE_ENV === "development";
let win: BrowserWindow | null = null;
let loadWin: any = null;

function createWin() {
  const { width, height } = screen.getPrimaryDisplay().bounds;
  // Menu.setApplicationMenu(null);
  // 创建浏览器窗口
  win = new BrowserWindow({
    width: 840,
    // width: width,
    height: 500,
    // height: height,
    frame: false,
    resizable: false,
    transparent: true,
    webPreferences: {
      preload: path.resolve(__dirname, "preload.js"),
      contextIsolation: true,
      webSecurity: false,
      sandbox: false,
    },
  });

  if (isDev) {
    win.loadURL(`http://localhost:8090`);
  } else {
    win.loadFile(path.resolve(__dirname, "index.html"));
  }

  win.webContents.once("dom-ready", () => {
    win?.show();
  });
  win.webContents.on("before-input-event", (event: any, input: any) => {
    if (input.key === "F12") {
      win.webContents.openDevTools();
    }
  });
  // loadWin.destroy();

  win.on("closed", () => {
    win = null;
  });
}

function createLoadWin() {
  Menu.setApplicationMenu(null);
  loadWin = new BrowserWindow({
    width: 840,
    height: 500,
    backgroundColor: "#222",
    frame: false,
    transparent: true,
    skipTaskbar: true,
    resizable: false,
    // webPreferences: { experimentalFeatures: true },
  });

  loadWin.loadFile(path.resolve(__dirname, "static/load/index.html"));

  loadWin.show();

  setTimeout(async () => {
    if (isDev) {
      try {
        await installExtension(VUEJS3_DEVTOOLS);
      } catch (e: any) {
        console.error("Vue Devtools failed to install:", e.toString());
      }
    }
    createWin();
  }, 2200);

  loadWin.on("closed", () => {
    loadWin = null;
  });
}

// app.isReady()
//   ? createLoadWin()
//   : app.on("ready", () => {
//       createLoadWin();
//     });

ipcMain.on("change-win-size", (event, args: string) => {
  // const { width, height } = screen.getPrimaryDisplay().workAreaSize;
  if (!win) return;
  const windowBounds = win.getBounds();
  const { width, height } =
    screen.getDisplayMatching(windowBounds).workAreaSize;

  let w = args === "big" ? width : 840;
  let h = args === "big" ? height : 500;
  if (args === "small") {
    win.setMinimumSize(w, h);
  }
  win.setSize(w, h);
  win.center();
});
ipcMain.on("window-min", () => {
  win.minimize();
});

function startExe(exePath: string) {
  console.log("主进程接收到的exe路径：", exePath);
  let checkPath = exePath.includes(".exe ")
    ? exePath.split(".exe ")[0] + ".exe"
    : exePath;
  const fileExists = fs.existsSync(checkPath);
  if (fileExists) {
    exec(exePath);
  } else {
    dialog.showErrorBox("tip", `${checkPath}不存在！`);
  }
}

ipcMain.on("startExe", (event, args: string) => {
  startExe(args);
});

app.on("ready", async () => {
  if (isDev) {
    try {
      await installExtension(VUEJS3_DEVTOOLS);
    } catch (e: any) {
      console.error("Vue Devtools failed to install:", e.toString());
    }
  }
  createWin();
});
