/* Copyright (c) Royal Holloway, University of London | Contact Blake Loring (blake@parsed.uk), Duncan Mitchell (Duncan.Mitchell.2015@rhul.ac.uk), or Johannes Kinder (johannes.kinder@rhul.ac.uk) for details or support | LICENSE.md for license details */

const { app, BrowserWindow, session } = require("electron");

const TestCaseParameters = JSON.parse(process.argv[process.argv.length - 1]);

app.commandLine.appendSwitch("ignore-certificate-errors");
app.commandLine.appendSwitch("disable-web-security");

// 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;

const createWindow = () => {
	// Create the browser window.
	mainWindow = new BrowserWindow({
		title: `ExpoSE ${process.argv[process.argv.length - 2]} ${process.argv[process.argv.length - 1]}`,
		width: 800,
		height: 600,
		webPreferences: {
			webSecurity: false
		}
	});

	mainWindow.on("page-title-updated", (e) => {
		e.preventDefault();
	});

	mainWindow.webContents.session.clearCache(function() {
		mainWindow.webContents.session.setProxy({proxyRules:"http://localhost:8080"}, function () {
			mainWindow.loadURL(process.argv[process.argv.length - 2]);
		});
	});

  mainWindow.webContents.session.webRequest.onBeforeSendHeaders((details, cb) => {

	  function rif(offset, o2) {
		  if (TestCaseParameters[offset]) { details.requestHeaders[o2] = TestCaseParameters[offset]; }
	  }

	  rif("userAgent", "User-Agent");
	  rif("cookie", "Cookie");

	  cb({ cancel: false, requestHeaders: details.requestHeaders });
  });

	// Emitted when the window is closed.
	mainWindow.on("closed", () => {
		mainWindow = null;
	});
};

// 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", createWindow);

// Quit when all windows are closed.
app.on("window-all-closed", () => {
	console.log("Window all closed");
	app.quit();
});

@@ -278,17 +278,8 @@
 ndow
-, session
  %7D =
@@ -1240,18 +1240,17 @@
 ;%0A%09%7D);%0A%0A
-  
+%09
 mainWind
@@ -1324,18 +1324,17 @@
  =%3E %7B%0A%0A%09
-  
+%09
 function
@@ -1354,18 +1354,17 @@
 o2) %7B%0A%09%09
-  
+%09
 if (Test
@@ -1388,17 +1388,82 @@
 fset%5D) %7B
- 
+%0A%09%09%09%09details.requestHeaders%5Bo2%5D = TestCaseParameters%5Boffset%5D;%0A%09%09%09%09
 details.
@@ -1471,32 +1471,46 @@
 equestHeaders%5Bo2
+.toLowerCase()
 %5D = TestCasePara
@@ -1528,20 +1528,21 @@
 et%5D;
- %7D%0A%09  
+%0A%09%09%09%7D%0A%09%09
 %7D%0A%0A%09
-  
+%09
 rif(
@@ -1570,18 +1570,17 @@
 ent%22);%0A%09
-  
+%09
 rif(%22coo
@@ -1600,12 +1600,129 @@
 %22);%0A
-%0A%09  
+%09%09rif(%22lastModified%22, %22Last-Modified%22);%0A%09%09rif(%22referer%22, %22Referer%22);%0A%09%09rif(%22origin%22, %22Origin%22);%0A%09%09rif(%22host%22, %22Host%22);%0A%09%09
 cb(%7B
@@ -1784,10 +1784,9 @@
 %7D);%0A
-  
+%09
 %7D);%0A

Format fixes