const { app, BrowserWindow, Menu, dialog, ipcMain, fs } = require('electron');
function createWindow () {
    const win = new BrowserWindow({
	width: 950,
	height: 580,
	icon: "/usr/lib/TrimSP/resources/app/icon.png",
	webPreferences: {
	    contextIsolation: false,
	    nodeIntegration: true,
	    nativeWindowOpen: true,
	    enableRemoteModule: true,
	}
    })

    
    let template = [
	{
	    label: 'File',
	    submenu: [
		{
		    label: 'Open',
		    id : 'openItem',
		    accelerator: 'CmdOrCtrl+O',
		    click () {
			dialog.showOpenDialog(win,
					      { title : "Load configuration file", 
						defaultPath : app.getPath('temp'),
						//buttonLabel : "Custom button",
						filters :[
						    {name: 'Config file type', extensions: ['cfg']},
						],
						properties: ['openFile']}
					     ).then(result => {
						 console.log(result.canceled);
						 console.log(result.filePaths);
						 if (!result.canceled) {
						     setImmediate(function() {
							 var focusedWindow = BrowserWindow.getFocusedWindow();
							 focusedWindow.webContents.send('openFile',result.filePaths);
						     });
						 }
					     }).catch(err => {
						 console.log(err);
					     })
		    }
		},
		{
		    label: 'Select Folder...',
		    accelerator: 'CmdOrCtrl+F',
		    click () {
			dialog.showOpenDialog(win,
					      { title: "Select folder",
						defaultPath :  app.getPath('temp'),
						properties:["openDirectory"]}
					     ).then(result => {
						 setImmediate(function() {
						     console.log(result.filePaths)
						     var focusedWindow = BrowserWindow.getFocusedWindow();
						     focusedWindow.webContents.send('selectFolder',result.filePaths);
						 });
					     }).catch(err => {
						 console.log(err);
					     })
		    }
		},
		{
		    label: 'Save',
		    accelerator: 'CmdOrCtrl+S',
		    click () {
			setImmediate(function() {
			    var focusedWindow = BrowserWindow.getFocusedWindow();
			    focusedWindow.webContents.send('saveFile','');
			});
		    }
		},
		{
		    label: 'Save As...',
		    accelerator: 'CmdOrCtrl+Shift+S',
		    click () {
			dialog.showSaveDialog(win,
					      { title : "Save configuration file", 
						defaultPath : app.getPath('temp'),
						filters :[
						    {name: 'Config file type', extensions: ['cfg']},
						    {name: 'All Files', extensions: ['*']}
						],
						properties: ['showOverwriteConfirmation']}
					     ).then(result => {
						 setImmediate(function() {
						     var focusedWindow = BrowserWindow.getFocusedWindow();
						     focusedWindow.webContents.send('saveFile',result.filePath);
						 });
					     }).catch(err => {
						 console.log(err);
					     })
		    }
		},
		{
		    label: 'Print',
		    accelerator: 'CmdOrCtrl+P',
		    click () {
			setImmediate(function() {
			    var focusedWindow = BrowserWindow.getFocusedWindow();
			    const options = {};
			    focusedWindow.webContents.print(options, (success, errorType) => {
				if (!success) console.log(errorType)
			    });
			});
		    }
		},
		{
		    role: 'quit'
		}
	    ]
	},
	{
	    role: 'editMenu'
	},
	{
	    label: 'Plot',
	    submenu: [
		{
		    label: 'Plot Profiles',
		    //accelerator: 'CmdOrCtrl+P P',
		    click () {
			dialog.showOpenDialog(win,
					      { title : "Select rge files", 
						filters :[
						    {name: 'Profile file type', extensions: ['rge']},
						    {name: 'All Files', extensions: ['*']}
						],
						properties: ['openFile', 'multiSelections']}
					     ).then(result => {
						 console.log(result.canceled);
						 console.log(result.filePaths);
						 if (!result.canceled) {
						     setImmediate(function() {
							 var focusedWindow = BrowserWindow.getFocusedWindow();
							 focusedWindow.webContents.send('plotProf',result.filePaths);
						     });
						 }
					     }).catch(err => {
						 console.log(err);
					     })
		    }
		},
		{
		    label: 'Plot Fractions',
		    //accelerator: 'CmdOrCtrl+P F',
		    click () {
			dialog.showOpenDialog(win,
					      { title : "Select sequence file", 
						filters :[
						    {name: 'Sequence file type', extensions: ['dat']},
						    {name: 'All Files', extensions: ['*']}
						],
						properties: ['openFile']}
					     ).then(result => {
						 console.log(result.canceled);
						 console.log(result.filePaths);
						 if (!result.canceled) {
						     setImmediate(function() {
							 var focusedWindow = BrowserWindow.getFocusedWindow();
							 focusedWindow.webContents.send('plotFrac',result.filePaths);
						     });
						 }
					     }).catch(err => {
						 console.log(err);
					     })
		    }
		}, 
		{
		    label: 'Plot Mean',
		    //accelerator: 'CmdOrCtrl+P M',
		    click () {
			dialog.showOpenDialog(win,
					      { title : "Select sequence file", 
						filters :[
						    {name: 'Sequence file type', extensions: ['dat']},
						    {name: 'All Files', extensions: ['*']}
						],
						properties: ['openFile']}
					     ).then(result => {
						 console.log(result.canceled);
						 console.log(result.filePaths);
						 if (!result.canceled) {
						     setImmediate(function() {
							 var focusedWindow = BrowserWindow.getFocusedWindow();
							 focusedWindow.webContents.send('plotMean',result.filePaths);
						     });
						 }
					     }).catch(err => {
						 console.log(err);
					     })
		    }
		}
	    ]
	},
	{
	    role: 'viewMenu'
	},
	{
	    role: 'windowMenu'
	},
	{
	    role: 'help',
	    submenu: [
		{
		    role: 'about'
		},
		{
		    label: 'Learn More',
		    click () { require('electron').shell.openExternal('http://electron.atom.io') }
		}
	    ]
	}
    ]
    let menu = Menu.buildFromTemplate(template)
    Menu.setApplicationMenu(menu)
    
    win.loadFile('TrimSP.html');
    // Comment the following line to start without Dev 
    // win.openDevTools();
}

app.whenReady().then(createWindow)
global.path = app.getAppPath();
//console.log("From main: ",global.path);

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

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})

// Reply to calls from browser button
ipcMain.on('browseFolder', (event, args) => {
    console.log('received a message: '+args);
    dialog.showOpenDialog({ title: "Select folder",
			    defaultPath : app.getPath('temp'),
			    properties:["openDirectory"]}
			 ).then(result => {
			     console.log(result)
			     setImmediate(function() {
				 var focusedWindow = BrowserWindow.getFocusedWindow();
				 focusedWindow.webContents.send('browseFolder',result.filePaths);
				 app.setPath('temp',result.filePaths[0]);
			     });
			 }).catch(err => {
			     console.log(err);
			 })
});

//ipcMain.on('browseFolder-send', (event, args) => {
//    dialog.showOpenDialog(null, args).then(filePaths => {
//	event.sender.dend('browseFolder', filePaths);
//    }).catch(err => {
//	console.log(err);
//    })
//});


//menuItem = menu.getMenuItemById('openItem');
//console.log(menuItem);
