/*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 === "REGISTER_INTEREST") {
		let interestList =
			(await browser.storage.local.get("interesetWindows"))
				.interesetWindows ?? [];
		// Already has interest!
		if (interestList.includes(sender.tab.id)) {
			return;
		}
		interestList.push(sender.tab.id);

		await browser.storage.local.set({
			interesetWindows: interestList,
		});

		return;
	}
	if (message.type === "GOT_INFO_R") {
		// TODO then send this information back to that page
		let interestList =
			(await browser.storage.local.get("interesetWindows"))
				.interesetWindows ?? [];

		interestList.forEach((a) => {
			browser.tabs.sendMessage(a, message);
		});
		return;
	}
	if (message.type === "R_GET_DATA_FROM_PAGE") {
	    let windowList = (await browser.storage.local.get("windows")).windows;
        if (!windowList) return;
	    const tab = await browser.tabs.get(windowList);
        browser.tabs.sendMessage(tab.id, {
            type: "GET_DATA_FROM_PAGE",
        });
        return;
    }
	if (message.type !== "MY_GET_URL") return;

	let windowList = (await browser.storage.local.get("windows")).windows;
	if (!windowList) {
		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);

	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,
	});
});

async function startup() {
	await browser.storage.local.set({
		windows: null,
		interesetWindows: [],
	});

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

	browser.menus.onClicked.addListener(async function (e, tab) {
		if (e.menuItemId === "mark-page") {
            await browser.storage.local.set({
                windows: tab.id,
            });
		}
	});
}

browser.runtime.onInstalled.addListener(startup);
browser.runtime.onStartup.addListener(startup);
