// 用于管理Electron里面的所有窗口
const electron = require('electron');
const log = require('electron-xlog');
const { app, BrowserWindow, ipcMain, remote, crashReporter } = require('electron');

var win_stack = [];
var is_crashed = false;

function getFocusWin() {
  for (var i = win_stack.length - 1; i >= 0; i--) {
    if (win_stack[i]['window'].isFocused()) {
      return win_stack[i];
    }
  }
}

function findWin(title) {
  for (var i = win_stack.length - 1; i >= 0; i--) {
    if (win_stack[i]['title'] == title) {
      return win_stack[i];
    }
  }
}

function removeWin(win) {
  var idx = -1;
  for (var i = win_stack.length - 1; i >= 0; i--) {
    if (win_stack[i]['window'] == win) {
      idx = i;
      break;
    }
  }
  if (idx > -1) {
    win_stack.splice(idx, 1);
  }
}

function setWinMax(win) {
    process.platform === 'darwin' && win.setResizable(true);
    win.maximize();
    win.setMovable(false);
    win.webContents.send('max', {});
    process.platform === 'darwin' && win.setResizable(false);
}

function setWinUnMax(win) {
    process.platform === 'darwin' && win.setResizable(true);
    win.unmaximize();
    win.setMovable(true);
    win.webContents.send('unmax', {});
    process.platform === 'darwin' && win.setResizable(false);
}

var swin = {
  init: function () {   // 全局属性
    // 添加调试入口
    electron.globalShortcut.register('CmdOrCtrl+F11', () => {
      focusWin = getFocusWin();
      if (typeof (focusWin) != 'undefined') {
        focusWin['window'].webContents.openDevTools();
      }
    })
    // 添加刷新机制
    electron.globalShortcut.register('CmdOrCtrl+F5', () => {
      focusWin = getFocusWin();
      if (typeof (focusWin) != 'undefined') {
        focusWin['window'].webContents.reload();
      }
    })
//    electron.globalShortcut.register('CmdOrCtrl+R', () => {
//      focusWin = getFocusWin();
//      if (typeof (focusWin) != 'undefined') {
//        focusWin['window'].webContents.reload();
//      }
//    })
    // 最小化登录窗口
    ipcMain.on('ComWin:Sys', function (event, msg, cmd) {
      focusWin = getFocusWin();
      if (typeof (focusWin) != 'undefined') {
        log.info("[TAG-WIN] common window command: " + cmd + ", win:" + focusWin['title']);
        if (cmd == "min") {
          focusWin['window'].minimize();
        } else if (cmd == "max") {
          log.info("[TAG-WIN] common window max with status: " + focusWin['max'] + ", win:" + focusWin['title']);
          if (typeof (focusWin['max']) == 'undefined' || !focusWin['max']) {
            setWinMax(focusWin['window']);
            focusWin['max'] = true;
          } else {
            setWinUnMax(focusWin['window']);
            focusWin['max'] = false;
          }
        } else {
          focusWin['window'].close();
        }
      }
    })
  },
  addWindow: function (title, parentTitle, width, height, file, isShow, data) {
    var win;
    var startTime = new Date();
    var win = findWin(title);
    var parentWin = findWin(parentTitle);
    if (typeof (win) != 'undefined') {  // 窗口已打开，避免重复打开
      return undefined;
    }
    if (typeof (parentWin) != 'undefined') {  // 是对话框
      win = new BrowserWindow({
        width: width,
        height: height,
        minWidth: width,
        minHeight: height,
        parent: parentWin['window'],
        show: isShow,
        autoHideMenuBar: true,
        frame: false,
        fullscreenable: false,
        resizable: false,
        webPreferences: {
          nodeIntegration: true
        }
      });
    } else {
      win = new BrowserWindow({
        backgroundColor: '#212224',
        width: width,
        height: height,
        minWidth: width,
        minHeight: height,
        maximizable: true,
        minimizable: true,
        resizable: false,
        show: false,
        autoHideMenuBar: true,
        frame: false,
        webPreferences: {
          nodeIntegration: true
        },
        backgroundColor: '#212224',
      });
    }
    // 加载文件
    win.loadFile(file);
    process.platform === 'darwin' && win.setResizable(false);
    //win.webContents.openDevTools();
    win.webContents.on('unresponsive', () => {  // 界面卡死时触发
      log.error("[TAG-WIN] window [" + title + "] unresponsive");
    })

    win.once('ready-to-show', () => {
      log.info("[TAG-WIN] event:ready-to-show->enter win: "+title+", show: "+isShow);
      if (isShow) {
        win.show();
      }
    })

    win.webContents.on('did-finish-load', () => {
      log.info("[TAG-WIN] event:did-finish-load->enter " + title + " cost " + (new Date() - startTime) + "ms" + ", show: " + isShow);
      win.webContents.send('start', data);
    })
    win.webContents.on('crashed', (events) => {
      is_crashed = true;
      for (var event in events) {
        log.info("[TAG-WIN] window " + title + " crashed info1: " + event + ", " + events[event]);
      }
    })
    win.on('minimize', ()=>{
      log.info("[TAG-WIN] window minimize: " + title);
    })
    win.on('closed', () => {
      removeWin(win);
      focusWin = win_stack[win_stack.length-1];
      if (focusWin && focusWin.title == 'WIN_DOCLIST'){
        focusWin = win_stack[win_stack.length-2];
      }
      if (typeof (focusWin) != 'undefined') {  // 窗口已打开，避免重复打开
        focusWin['window'].webContents.send('resume', null);
        log.info("[TAG-WIN] window closed: " + title+", cur window: "+focusWin['title']);
      }else{
        log.info("[TAG-WIN] window closed: " + title+"/"+focusWin);
      }
    })
    win_stack.push({ title: title, window: win, show: isShow });
    return win;
  },
  closeWindow: function (title) {
    var win = findWin(title);
    if (typeof (win) != 'undefined') {
      win['window'].close();
    }
  },
  closeAllWindow: function(){
    for (var i = win_stack.length - 1; i >= 0; i--) {
      win_stack[i]['window'].close();
    }
  },
  findWindow: function (title) {
    var win = findWin(title);
    if (typeof (win) != 'undefined') {
      return win['window'];
    }
  },
  resumeWindow: function(title){
    var win = findWin(title);
    if (typeof (win) != 'undefined') {
      win['window'].webContents.send('resume', null);
    }
  },
  reloadWindow: function (title, file, param) {
    let win = findWin(title);
    if (typeof (win) != 'undefined') {
      log.info("[TAG-Win] load " + file);
      // win.window.loadFile(file);
      let contents = win.window.webContents;
      contents.loadFile(file);
      //contents.loadFile(file, {
      //  query: JSON.parse(param)
      //});
    }
  },
  goback: function (title) {
    let win = findWin(title);
    if (typeof (win) != 'undefined') {
      log.info("[TAG-Win] goback " + title);
      let contents = win.window.webContents;
      if (contents.canGoBack()) {
        contents.goBack();
      }
    }
  },
  showWindow: function (title, isShow) {
    var win = findWin(title);
    if (typeof (win) != 'undefined') {
      if (isShow) {
        win['window'].show();
        win['window'].webContents.send('show', null);
        log.info("[TAG-WIN] window show: " + title);
      } else {
        win['window'].hide();
        win['window'].webContents.send('hide', null);
        log.info("[TAG-WIN] window hide: " + title);
      }
    }
    win['show'] = isShow;
    return win['window'];
  },
  setWindowFullScreen: function (title, isFullScreen) {
    var win = findWin(title);
    if (typeof (win) != 'undefined') {
      win['window'].setFullScreen(isFullScreen);
    }
  },
  boardcastWinMsg: function (msg, param1, param2, param3, param4) {
    for (var i = win_stack.length - 1; i >= 0; i--) {
      win_stack[i]['window'].webContents.send(msg, param1, param2, param3, param4);
    }
  },
  activeTopWin: function(){
    focusWin = win_stack[win_stack.length-1];
    if (typeof (focusWin) != 'undefined') {  // 窗口已打开
      if (focusWin['window'].isMinimized()){
        focusWin['window'].restore();
      }
      focusWin['window'].focus();
    }
  },
  checkStatus: function(){
    this.debugWindow();
    if (is_crashed){
      return false;
    }
    for (var i = win_stack.length - 1; i >= 0; i--) {
      if (win_stack[i]['show']){
        return true;
      }
    }
    return false;
  },
  debugWindow: function(){
    for (var i = win_stack.length - 1; i >= 0; i--) {
      log.info("[TAG-WIN] debugWindow=>window: "+win_stack[i]['title']+", visible: "+win_stack[i]['show']);
    }
  }
}

module.exports = swin;
