/*browser.browserAction.onClicked.addListener(function (e) {
	console.log("This is a nice test!", e);
});*/

browser.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
	if (message.type !== "MY_GET_URL") return;

	let windowList = (await browser.storage.local.get("windows")).windows ?? [];
	if (windowList.length !== 1) {
		browser.tabs.sendMessage(sender.tab.id, {
			type: "MY_GET_URL_R",
			error: "Invalid number of pages marked as target",
			data: windowList,
		});
		return;
	}

	const tab = await browser.tabs.get(windowList[0]);

	browser.tabs.sendMessage(tab.id, {
		type: "GET_DATA_FROM_PAGE",
	});

	browser.tabs.sendMessage(sender.tab.id, {
		type: "MY_GET_URL_R",
		url: tab.url,
		all_data: tab,
	});
});

browser.runtime.onInstalled.addListener(async () => {
	console.log(browser);

	await browser.storage.local.set({
		windows: [],
	});

	// Clear the menus from the prev install
	browser.menus.removeAll();
	browser.menus.create({
		id: "mark-page",
		title: "Mark Page As the Glassdoor target",
		contexts: ["all"],
	});

	browser.menus.create({
		id: "mark-page-clear",
		title: "Clear Marked Pages",
		contexts: ["all"],
	});

	browser.menus.onClicked.addListener(async function (e, tab) {
		let windowList =
			(await browser.storage.local.get("windows")).windows ?? [];

		console.log("test", e.menuItemId, e.menuItemId === "mark-page-clear");

		if (e.menuItemId === "mark-page") {
			console.log("marking page", tab);
			if (windowList.includes(tab.id)) {
				windowList = windowList.filter((a) => a !== tab.id);
			} else {
				windowList.push(tab.id);
			}
		} else if (e.menuItemId === "mark-page-clear") {
			windowList = [];
			console.log("clear");
		}
		await browser.storage.local.set({
			windows: windowList,
		});
	});
});
