// Colors
const bold      = (str) => `\x1b[1m${str}\x1b[0m`;
const underline = (str) => `\x1b[4m${str}\x1b[0m`;
const red       = (str) => `\x1b[31m${str}\x1b[0m`;
const green     = (str) => `\x1b[32m${str}\x1b[0m`;
const yellow    = (str) => `\x1b[33m${str}\x1b[0m`;
const blue      = (str) => `\x1b[34m${str}\x1b[0m`;
const gray      = (str) => `\x1b[2m${str}\x1b[0m`;
const nothing   = (str) => str;
const getConsoleColor = { "log": green, "warn": yellow, "error": red }

const logMainInfo = (str) => console.log("\n" + underline(str));
const logMainError = (str) => console.log("\n" + underline(red(str)));

const delay = (time) => {
	return new Promise(resolve => setTimeout(resolve, time));
}

const hookPageEvents = async function (page, id) {
	page.on("console", (msg) => {
		var msgType = msg.type();
		var color   = getConsoleColor[msgType] || nothing;
		console.log(`${bold(`[T${id}]>`)} ${color(`console.${msgType}`.padEnd(17))} ${bold("|")} ${msg.text()}`);
	});

	page.on("framenavigated", (frame) => {
		if (frame === page.mainFrame()) {
			console.log(`${bold(`[T${id}]>`)} ${blue("navigating".padEnd(17))} ${bold("|")} ${frame.url()}`);
		}
	});
}

let tabs = [];
let nbSW = 0;
const handleTargetCreated = async function (target) {
	if (!["BidiPageTarget", "BidiPage"].includes(target.constructor.name)) {
		return;
	}
	const page = target.constructor.name === "BidiPageTarget" ? await target.page() : target;

	if (tabs.length > 5) { // pages[0] doesn't count since it's not being used.
		logMainError("You can't open more than 5 tabs!");
		await this.close();
		process.exit(1);
	}
	tabs.push(target._targetId);
	console.log(`${bold(`[T${tabs.length}]>`)} ${gray("New tab created!")}`);
	console.log(`${bold(`[T${tabs.length}]>`)} ${blue("navigating".padEnd(17))} ${bold("|")} ${page.url()}`);
	await hookPageEvents(page, tabs.length);

}

const handleTargetDestroyed = async function (target) {
	if (target.type() === "page") {
		console.log(`${bold(`[T${tabs.indexOf(target._targetId)+1}]>`)} ${gray("Tab closed!")}`);
	}
}

module.exports = {
	delay,
	handleTargetCreated,
	handleTargetDestroyed,
	logMainInfo,
	logMainError
}