const electron = require('electron');
const configuration = require('./config.json');
const URL = require('./url.json');
const path = require('path');
const app = electron.app; //控制应用生命周期的模块。
const BrowserWindow = electron.BrowserWindow; //创建原生浏览器窗口的模块
const Menu = electron.Menu; //创建菜单
const globalShortcut = electron.globalShortcut;
const session = electron.session;

const width = configuration.width || 960;
const height = configuration.height || 560;
const keyboardResizable = configuration.keyboardResizable || false;
const resizable = configuration.resizable || false;
let appUrl = URL.verseUrl[0].url;

//保持一个对于 window 对象的全局引用，不然，当 JavaScript被 GC，
// window 会被自动地关闭
var mainWindow = null;


/* 添加flash插件 */

let pluginName
let pluginVersion
switch (process.platform) {
  case 'win32':
    //pluginName = 'pepflashplayer64_24_0_0_186.dll'
    //pluginVersion = '24.0.0.186'
    pluginName = 'pepflashplayer64_26_0_0_131.dll'
    pluginVersion = '26.0.0.131'
    //pluginName = 'pepflashplayer32_27_0_0_187.dll'
    //pluginVersion = '27.0.0.187'
    break
  case 'darwin':
    pluginName = 'PepperFlashPlayer.plugin'
    pluginVersion = '21.0.0.204'
    break
  //case 'linux':
    //pluginName = 'libpepflashplayer.so'
    //break
}
app.commandLine.appendSwitch('ppapi-flash-path', path.join(__dirname, 'plugins', pluginName))
app.commandLine.appendSwitch('ppapi-flash-version', pluginVersion)
app.commandLine.appendSwitch('--disable-http-cache')


/* 启用窗口缩放 */

function enableResize() {
  let resize = false
  globalShortcut.register('CommandOrControl+=', () => {
    if (mainWindow) {
      if (resize) return
      resize = true
      let level = .05
      let bounds = mainWindow.webContents.getOwnerBrowserWindow().getBounds()
      let width = Math.floor(bounds.width * (1 + level))
      let height = Math.floor(bounds.height * (1 + level))
      mainWindow.setSize(width, height)
      mainWindow.center();
      resize = false
    }
  })
  globalShortcut.register('CommandOrControl+-', () => {
    if (mainWindow) {
      if (resize) return
      resize = true
      let level = .05
      let bounds = mainWindow.webContents.getOwnerBrowserWindow().getBounds()
      let width = Math.floor(bounds.width * (1 - level))
      let height = Math.floor(bounds.height * (1 - level))
      mainWindow.setSize(width, height)
      mainWindow.center();
      resize = false
    }
  })
  globalShortcut.register('CommandOrControl+0', () => {
    if (mainWindow) {
      if (resize) return
      resize = true
      mainWindow.setSize(width, height)
      mainWindow.center();
      resize = false
    }
  })
}


/* 定义微端菜单 */

function createVersionMenu() {
  let menu = [];
  URL.officialUrl.forEach((item) => {
    menu.push({
      label: item.label,
      click: () => {
        appUrl = item.url;
        mainWindow.loadURL(appUrl);
      },
    });
  });
  menu.push({type: 'separator'});
  URL.mirrorUrl.forEach((item) => {
    menu.push({
      label: item.label,
      click: () => {
        appUrl = item.url;
        mainWindow.loadURL(appUrl);
      },
    });
  });
  menu.push({type: 'separator'});
  URL.verseUrl.forEach((item) => {
    menu.push({
      label: item.label,
      click: () => {
        appUrl = item.url;
        mainWindow.loadURL(appUrl);
      },
    });
  });
  return menu;
}

function createExternalMenu() {
  let menu = [];
  URL.externalUrl.forEach((item) => {
    menu.push({
      label: item.label,
      click: () => {
        let childWindow = new BrowserWindow({
          width: item.width,
          height: item.height,
          autoHideMenuBar: true,
          resizable: true,
          fullscreenable: true,
          menuBarVisible: false,
        });
        childWindow.loadURL(item.url);
      },
    });
  });
  menu.push({type: 'separator'});
  menu.push({
    label: '官服更新公告',
    click: () => {
      let childWindow = new BrowserWindow({
        autoHideMenuBar: true,
        resizable: true,
        fullscreenable: true,
        menuBarVisible: false,
      });
      childWindow.loadURL(URL.informationUrl);
    },
  });
  return menu;
}

function createMenu() {
  

  let template = [
    {
      label: '版本/节点选择',
      submenu: createVersionMenu(),
    },
    {
      label: '页面重载',
      submenu: [
        {
          label: '刷新页面（F5）',
          click: () => {
            mainWindow.loadURL(appUrl);
          },
        },
        {
          label: '清除缓存并刷新页面（Ctrl+F5）',
          click: () => {
            session.defaultSession.clearCache();
            mainWindow.loadURL(appUrl);
          },
        },
      ],
    },
    {
      label: '实用链接',
      submenu: createExternalMenu(),
    },
    {
      label: '开发者工具',
      click: () => {
        if (mainWindow) {
          mainWindow.webContents.openDevTools();
        }
      },
    },
  ];
  return Menu.buildFromTemplate(template);
}


// 当所有窗口被关闭了，退出。
app.on('window-all-closed', function() {
  // 在 OS X 上，通常用户在明确地按下 Cmd + Q 之前
  // 应用会保持活动状态
  if (process.platform != 'darwin') {
    app.quit();
  }
});

// 当 Electron 完成了初始化并且准备创建浏览器窗口的时候
// 这个方法就被调用
app.on('ready', () => {
  // 创建浏览器窗口。
  mainWindow = new BrowserWindow({
    width,
    height,
    useContentSize: true,
    autoHideMenuBar: false,
    resizable: resizable,
    fullscreenable: resizable,
    menuBarVisible: true,
    webPreferences: {
      plugins: true,
      webPreferences: {
        plugins: true,
        contextIsolation: false
      }
    }
  });

  mainWindow.webContents.on('will-prevent-unload', (event) => {
    const choice = electron.dialog.showMessageBoxSync(mainWindow, {
      type: 'question',
      buttons: ['留在此页', '离开此页'],
      message: '确定要离开此页面吗？'
    });
    if (choice === 1) {
      event.preventDefault();
    }
  });
  
  // 加载应用的 index.html
  //mainWindow.loadURL('file://' + __dirname + '/index.html');
  mainWindow.loadURL(appUrl);

  // 挂载菜单
  let menu = createMenu();
  Menu.setApplicationMenu(menu);

  globalShortcut.register('F5', () => {
    if (mainWindow) {
      mainWindow.loadURL(appUrl);
    }
  })
  globalShortcut.register('CommandOrControl+F5', () => {
    if (mainWindow) {
      session.defaultSession.clearCache();
      mainWindow.loadURL(appUrl);
    }
  })
  if (keyboardResizable) {
    enableResize()
  }

  // 打开开发工具
  globalShortcut.register('CommandOrControl+F12', () => {
    if (mainWindow) {
      mainWindow.webContents.openDevTools();
    }
  });

  // 当 window 被关闭，这个事件会被发出
  mainWindow.on('closed', function() {
    // 取消引用 window 对象，如果你的应用支持多窗口的话，
    // 通常会把多个 window 对象存放在一个数组里面，
    // 但这次不是。
    mainWindow = null;
    app.quit();
  });

});
