const electron = require('electron')
const app = electron.app;
const path = require('path');
const shell = electron.shell;
const dialog = electron.dialog;
function downloadFile( mainWindow ){
	mainWindow.webContents.session.on('will-download', (e, item) => {
		//获取文件的总大小
	   	const totalBytes = item.getTotalBytes();
		//设置文件的保存路径，此时默认弹出的 save dialog 将被覆盖
		// console.log(decodeURI(item.getFilename()));
	   	const filePath = path.join( app.getPath('downloads'), decodeURI(item.getFilename()) );
	   	item.setSavePath(filePath);
		//监听下载过程，计算并设置进度条进度
	   	item.on('updated', () => {
		   	mainWindow.webContents.send('download-process', {filename : decodeURI(item.getFilename()) , process:item.getReceivedBytes() / totalBytes} );
		 	mainWindow.setProgressBar(item.getReceivedBytes() / totalBytes);
	   	});
		//监听下载结束事件
	   	item.on('done', (e, state) => {
			//如果窗口还在的话，去掉进度条
		 	if (!mainWindow.isDestroyed()) {
		     		mainWindow.setProgressBar(-1);
		 	}
			//下载被取消或中断了
		 	if (state === 'interrupted') {
		     		dialog.showErrorBox('下载失败', `文件 ${item.getFilename()}下载失败`);
		 	}
		 	if (state === 'completed') {
				//app.dock.bounce(filePath);
				shell.showItemInFolder(filePath);
		 	}
	   	});
	});
}
exports.filewatch = downloadFile;
