const electron = require('electron')
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow
const ipcMain = electron.ipcMain

const path = require('path')
const url = require('url')

const Menu = electron.Menu;
const Tray = electron.Tray;
const MenuItem = electron.MenuItem;
const globalShortcut = electron.globalShortcut;
const downloadFile = require('./js/downloadfile');
const menuTpl = require('./js/template');
const platform = {
      OSX: process.platform === 'darwin',
      Windows: process.platform === 'win32',
      Linux: process.platform === 'linux'
}
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow
let appIcon = null
let contextMenu
function createWindow () {
      // Create the browser window.
      mainWindow = new BrowserWindow({
            width: 965,
            height: 630,
            minWidth : 965,
            minHeight : 630,
            maxWidth : 1400,
            maxHeight : 1000,
            center : true,
            titleBarStyle : 'hidden-inset',
            title : '阿米协同',
            icon: platform.OSX ? (__dirname + '/images/tray.png') : (__dirname + '/images/logo.png'),
            // show : false,
            frame : platform.OSX ? false : true,
            webPreferences : {
                  preload: path.join(__dirname, 'js', 'preload.js'),
                  plugins: true
            }
      })
      createMenu();

      mainWindow.loadURL('http://team-pc.cloud.hoge.cn/#/index?timestamp='+ (new Date()).getTime() )
      // Open the DevTools.
      // mainWindow.webContents.openDevTools()
      mainWindow.on('ready-to-show', function() {
            mainWindow.show();
            mainWindow.focus();
      })

      // Emitted when the window is closed.
      mainWindow.on('close', function (event) {
            // Dereference the window object, usually you would store windows
            // in an array if your app supports multi windows, this is the time
            // when you should delete the corresponding element.
            if( process.platform == 'darwin' ){
                  app.hide();
            }else{
                  mainWindow.hide();
            }
            event.preventDefault();
      })
      mainWindow.on('closed', function (event) {
            // Dereference the window object, usually you would store windows
            // in an array if your app supports multi windows, this is the time
            // when you should delete the corresponding element.
            mainWindow = null
      })
      mainWindow.on('unresponsive' , function (){
            app.exit();
      })
      downloadFile.filewatch( mainWindow );
}

//消息通知 dock上数字显示
ipcMain.on('unread-message-count-changed', (event, arg) => {
    let number = parseInt(arg, 10)
    let iconFile
    number = isNaN(number) ? 0 : number

    if (platform.OSX) {
      setBadge(number)
    }
    else if (platform.Windows){
      setTray(number)
    }
  })
  function setBadge (unreadCount) {
        let text

        if (unreadCount < 1) {
          text = ''
        } else if (unreadCount > 99) {
          text = '99+'
        } else {
          text = unreadCount.toString()
        }

        app.dock.setBadge(text)
        appIcon.setTitle(text == '' ? '' : text)
}
let blink;
function setTray (unreadCount) {
        let iconFile = ['tray.png','logo.png']
        let flag
        if(unreadCount > 0){
          if(!blink){
                appIcon.displayBalloon({
                      title : '阿米协同',
                      content : '您有新短消息,请及时查看!'
                })
            blink = setInterval(function(){
              flag = !flag
              appIcon.setImage(path.join(__dirname, 'images', iconFile[flag ? 1 : 0]))
            },500)
          }
        }
        else{
           if(blink){
              clearInterval(blink)
           }
           blink = null
           appIcon.setImage(path.join(__dirname, 'images', iconFile[1]))
        }
}
ipcMain.on('webQuit', () => {
    if (platform.OSX){
         setBadge(0)
      //    appIcon.setImage(path.join(__dirname, 'res', 'Mac_Template.png'))
    } else if (platform.Windows){
         setTray(0)
    }
})

function createMenu(){
      if (appIcon) appIcon.destroy();
      appIcon = new Tray( platform.OSX ? (__dirname + '/images/tray.png') : (__dirname + '/images/logo.png') );
      if( process.platform == 'darwin' ){
            appIcon.setPressedImage(__dirname + '/images/tray-empty.png');
      }
      appIcon.setToolTip('阿米协同');
      contextMenu = menuTpl.menuTemp( mainWindow ,appIcon).contextMenu;
      appIcon.setContextMenu(contextMenu);
      appIcon.on('click' , function(){
            mainWindow.show();
            mainWindow.focus();
      })
      if (process.platform === 'darwin') {
            var tpl = menuTpl.menuTemp( mainWindow,appIcon ).MenuItems;
            var osxMenu = Menu.buildFromTemplate(tpl);
            Menu.setApplicationMenu(osxMenu);
      }
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', function(){
      createWindow();
      require('./js/powerMonitor');
      require('./auto-updater');
})

// Quit when all windows are closed.
app.on('window-all-closed', () => {
      // On OS X it is common for applications and their menu bar
      // to stay active until the user quits explicitly with Cmd + Q
      if (process.platform !== 'darwin') {
            app.quit()
      }
})
app.on('before-quit' , () => {
      app.exit();
})
app.on('activate', () => {
      // On OS X it's common to re-create a window in the app when the
      // dock icon is clicked and there are no other windows open.
      if (mainWindow === null) {
            createWindow()
      }
      if( !mainWindow.isVisible() ){
            mainWindow.show();
      }
})

ipcMain.on('notification-click', () => {
      mainWindow.show();
      app.emit('activate');
})
ipcMain.on('screenShot', () => {
      takeScreenshot()
})
function takeScreenshot() {
      mainWindow.webContents.send('screenshot')
}
