const { BrowserWindow, protocol } = require("electron");
const path = require("path");

module.exports = () => {
  let win;

  let init = opts => {
    createWindow(opts);
  };

  let createWindow = opts => {
    const winURL =
      process.env.NODE_ENV === "development"
        ? `http://127.0.0.1:5501`
        : `file://${__dirname}/index.html`;

    win = new BrowserWindow({
      height: 186,
      useContentSize: true,
      resizable: true,
      width: 920,
      frame: false,
      title: "拉比克",
      show: false,
      skipTaskbar: true,
      webPreferences: {
        webSecurity: false,
        enableRemoteModule: true,
        backgroundThrottling: false,
        contextIsolation: false,
        webviewTag: true,
        devTools: true,
        nodeIntegration: true, // 在网页中集成Node
        preload: `${path.resolve(__dirname, "./preload.js")}`
      }
    });

    win.loadURL(winURL);

    protocol.interceptFileProtocol(
      "image",
      (req, callback) => {
        const url = req.url.substr(8);
        callback(decodeURI(url));
      },
      error => {
        if (error) {
          console.error("Failed to register protocol");
        }
      }
    );

    win.once("ready-to-show", () => win.show());
    win.on("closed", () => {
      win = undefined;
    });
    win.on("blur", () => {
      win.hide();
    });
  };

  let getWindow = () => win;

  return {
    init,
    getWindow
  };
};
