// TODO Append location to PATH

const path = require('path');
const fs = require('fs');
const {Builder, By, Key, until} = require('selenium-webdriver');
const firefox   = require('selenium-webdriver/firefox');

const geckodriverPath = path.resolve(__dirname, "geckodriver");

// We launch a browser instance and then start an activity timer.
// We shut down the browser after a period of inactivity, to
// save memory.
let driver = null;
let timer = null;

function resetTimer () {
	clearTimeout(timer);
	timer = setTimeout(shutdown, 120000); // Yup, hardcoded to two minutes. For now anyway
}

async function launch () {
	resetTimer();
	if (!driver) {
		console.log("Launching Firefox");
		const options = new firefox.Options();
		driver = await new Builder()
			.forBrowser('firefox')
			.setFirefoxService(new firefox.ServiceBuilder(geckodriverPath))
			.setFirefoxOptions(options.headless())
			.build();
	}
}

async function shutdown () {
	if (driver) {
		console.log("Shutting down Firefox");
		// This is an attempt at avoiding a race condition if someone
		// makes a call and resets the timer while the shutdown is in
		// progress.
		const d = driver;
		driver = null;
		await d.quit();
	}
}

async function url2pdf (url) {
	await launch();
	await driver.get(url);
	return await driver.printPage({width: 21.0, height: 29.7});
}

module.exports = { url2pdf };
