import { dialog, Menu, Tray, app, shell } from "electron";
import path from "path";
import pkg from "../../package.json";
import os from "os";
import { commonConst } from "./common/utils";

function createTray(window) {
  return new Promise((resolve, reject) => {
    let icon;
    if (commonConst.macOS()) {
      icon = "./icon@3x.png";
    } else if (commonConst.windows()) {
      icon = parseInt(os.release()) < 10 ? "./icon@3x.png" : "./icon@3x.png";
    } else {
      icon = "icon@3x.png";
    }
    const appIcon = new Tray(path.join(__static, icon));
    const contextMenu = Menu.buildFromTemplate([
      {
        label: "注册",
        click() {
          shell.openExternal("https://passport.csdn.net/newlogin?code=mobile");
        }
      },
      {
        label: "帮助文档",
        click: () => {
          process.nextTick(() => {
            shell.openExternal(
              "https://yre5673znb.feishu.cn/docs/doccnMnLv3iZ3epFvjXprnPum3b"
            );
          });
        }
      },
      {
        label: "意见反馈",
        click: () => {
          process.nextTick(() => {
            shell.openExternal("https://www.wenjuan.com/s/UZBZJvmzhg/");
          });
        }
      },
      { type: "separator" },
      {
        label: "显示窗口",
        accelerator: "Alt+R",
        click() {
          window.show();
        }
      },
      {
        label: "偏好设置",
        click() {
          window.show();
          window.webContents.send("tray-setting");
        }
      },
      {
        label: "关于",
        click() {
          dialog.showMessageBox({
            title: "Quicker",
            message: "即刻",
            detail: `Version: ${pkg.version}\nAuthor: libai`
          });
        }
      },
      { type: "separator" },
      {
        label: "重启",
        click() {
          app.relaunch();
          app.quit();
        }
      },
      {
        role: "quit",
        label: "退出"
      }
    ]);
    appIcon.on("click", () => {
      appIcon.popUpContextMenu(contextMenu);
    });
    appIcon.setContextMenu(contextMenu);

    resolve(appIcon);
  });
}

export default createTray;
