const fs = require('fs') ;
const path = require('path');
const electron = require('electron');
const {app} = electron;
const {BrowserWindow} = electron;
const {ipcMain} = require('electron');
const Logger = require('./lib/logger.js');

let winMain;
let winLoad;
let packageInfo;

//app.commandLine.appendSwitch('no-sandbox');

/**
 * 创建主窗口
 */
function createMainWindow(port) {
  require('./lib/ipcMain.js');

  var electronScreen = electron.screen;
  var size = electronScreen.getPrimaryDisplay().workAreaSize;
  winMain = new BrowserWindow({width: size.width, height: size.height,minWidth: 1200, minHeight: 720,
    resizable: true, frame: true, autoHideMenuBar:true,
    webPreferences:{
      contextIsolation: false,
      preload: path.join(global.rootDir, '/preload.js')
  }});
  winMain.loadURL(`file://${global.rootDir}/node_modules/taskbuilder-renderer/index.html`);
  global.winMain = winMain;
  winMain.maximize();
  if(global.clientConfig.isDebug) winMain.webContents.openDevTools();
  winMain.on('closed', () => {
    winMain = null;
    winLoad.close();
  });
}

/**
 * 检查更新
 * @return {[type]} [description]
 */
function checkUpdate() {
  //调试时不启用自动更新
  if(global.clientConfig.isDebug) {
    setTimeout(function(){
      winLoad.hide();
      createMainWindow();
    }, 5000);
    return;
  }

  //检查是否有新版本
  const Service = require('./lib/service.js');
  var service = new Service();
  service.serverHost = "www.taskbuilder.org";
  service.request("tb/service/getLastVersion", null, function(req, res) {
    //如果有新版本，弹窗提示
    if(packageInfo.version!=res.lastVersion) {
      const dialogOpts = {
        type: 'info',
        buttons: ['确定', '取消'],
        title: '更新提示',
        message: '发现新的版本，是否升级？'
      }

      const { dialog } = require('electron');
      dialog.showMessageBox(dialogOpts).then((returnValue) => {
        //如果确定更新，则启动更新程序
        if (returnValue.response === 0) {
          winLoad.webContents.executeJavaScript("startUpdate()");
          let Updater = require('./lib/updater.js');
          let updater = new Updater();
          try {
            updater.update(function(err) {
              if(err) logger.log(err);
              winLoad.hide();
              createMainWindow();
            });
          } catch(err) {
            logger.log(err.message);
            winLoad.hide();
            createMainWindow();
          }
        } else { //如果选择不更新
          setTimeout(function(){
            winLoad.hide();
            createMainWindow();
          }, 1000);
        }
      })
    } else {
      setTimeout(function(){
        winLoad.hide();
        createMainWindow();
      }, 3000);
    }
  });
}

/**
 * 显示加载窗口
 * @return {[type]} [description]
 */
function showLoadWindow() {
  var electronScreen = electron.screen;
  var size = electronScreen.getPrimaryDisplay().workAreaSize;
  winLoad = new BrowserWindow({width: 640, height: 480,
    resizable: false, frame: false, autoHideMenuBar:true, show: false
  });
  let loadPageUrl = `file://${global.rootDir}/node_modules/taskbuilder-renderer/loadPage.html`;
  //页面加载完成后检查是否有新版本
  winLoad.webContents.on("did-finish-load", function() {
    winLoad.webContents.executeJavaScript("document.getElementById('divVersion').innerText = 'version: "+packageInfo.version+"'");
    winLoad.show();
    checkUpdate();
  });
  winLoad.loadURL(loadPageUrl);
}

//下面这样代码可以禁用Chromium浏览器的跨域访问安全限制
//保证iframe内的本地页面可以和父页面进行互动访问
app.commandLine.appendSwitch('disable-site-isolation-trials');

// 当Electron完成初始化后该方法将会被调用。
// 有些API只能在该事件发生后才能被使用。
app.on('ready', function() {
  global.tempDir = "temp";

  //启动日志服务
	global.logger = new Logger();
	global.logger.start();

	logger.log('加载配置信息...');
  global.clientConfig = require('../../../../config.json');
  global.curServer = null;
  if(global.clientConfig.servers && global.clientConfig.servers.length>0)
    global.curServer = global.clientConfig.servers[0];

  packageInfo = require("../taskbuilder-renderer/package.json");
  
  showLoadWindow();
});

// 当所有的窗口被关闭后退出应用
app.on('window-all-closed', () => {
  logger.log('关闭所有窗口，退出应用。');
  //对于OS X系统，应用和相应的菜单栏会一直激活直到用户通过Cmd + Q显式退出
  if (process.platform !== 'darwin') {
    logger.isRunning = false;
    app.quit();
  }
});

app.on('activate', () => {
  // 对于OS X系统，当dock图标被点击后会重新创建一个app窗口，并且不会有其他窗口打开
  if (winLogin === null) {
    logger.log('打开窗口...');
    createMainWindow();
  }
});