import { app, BrowserWindow, ipcMain, Menu, Tray, nativeImage } from 'electron'
let tray = null;
let path = require("path")
let icon
let iconS
/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
	icon = nativeImage.createFromPath(path.join(__dirname, '../../../icon.png'))
	iconS = nativeImage.createFromPath(path.join(__dirname, '../../../empty.png'))
	global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
} else {
	icon = nativeImage.createFromPath('build/icons/icon.png')
	iconS = nativeImage.createFromPath('build/icons/empty.png')
}

let mainWindow
const winURL = process.env.NODE_ENV === 'development'
	? `http://localhost:9080`
	: `file://${__dirname}/index.html`

function createWindow() {
	let timer = null
	let count = 0;

	tray = new Tray(icon);
	const trayMenuTemplate = [
		{
			label: '退出',
			click: function () {
				if (tray) {
					tray.destroy()
				}
				app.exit(0)
			}
		}
	]
	// 图标的上下文菜单
	const contextMenu = Menu.buildFromTemplate(trayMenuTemplate)
	// 设置此托盘图标的悬停提示内容
	tray.setToolTip('欢迎使大博客服系统')
	// 设置此图标的上下文菜单
	if (process.platform === 'win32' || process.platform === 'win64') {
		tray.setContextMenu(contextMenu)
	}


	ipcMain.on('haveMessage', (event,arg) => {
		mainWindow.flashFrame(true)
		timer = setInterval(() => {
			count += 1
			if (count % 2 === 0) {
				tray.setImage(icon)
			} else {
				tray.setImage(iconS) // 创建一个空的nativeImage实例
			}
		}, 500)
	})
	tray.on('click', () => {
		mainWindow.flashFrame(false)
		if (mainWindow.isVisible()) {
			mainWindow.hide()
		} else {
			mainWindow.show()
			tray.setImage(icon)
			clearInterval(timer)
			timer = null
			count = 0
		}
	})
	/**
	 * Initial window options
	 */
	mainWindow = new BrowserWindow({
		height: 563,
		useContentSize: true,
		width: 1000,
	})

	mainWindow.loadURL(winURL)

	mainWindow.on('closed', () => {
		mainWindow = null
	})
}

app.on('ready', createWindow)

app.on('window-all-closed', () => {
	if (process.platform !== 'darwin') {
		app.quit()
	}
})

app.on('activate', () => {
	if (mainWindow === null) {
		createWindow()
	}
})

/**
 * Auto Updater
 *
 * Uncomment the following code below and install `electron-updater` to
 * support auto updating. Code Signing with a valid certificate is required.
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
 */

/*
import { autoUpdater } from 'electron-updater'

autoUpdater.on('update-downloaded', () => {
  autoUpdater.quitAndInstall()
})

app.on('ready', () => {
  if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
})
 */
