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

        let windowList = (await browser.storage.local.get("windows")).windows;
        if (windowList) {
            console.log("here sending got interest");
            browser.tabs.sendMessage(sender.tab.id, {
                type: "GOT_INTEREST",
            });
        }
        return;
    }
    if (message.type === "AUTOLOAD_NOTIFY_URL") {
        // 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, {
                type: "MY_GET_URL_R",
                url: message.url,
            });
        });
        return;
    }
    if (
        message.type === "GOT_INFO_R" ||
        message.type === "AUTOLOAD_FOUND_GLASSDOOR_SEARCH"
    ) {
        // 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 === "CHANGE_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: "CHANGE_PAGE",
            new_url: message.new_url,
        });
        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() {
    console.log("Exp startup application");
    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.runtime.onInstalled.addListener(startup);
browser.runtime.onStartup.addListener(startup);
browser.runtime.onConnect.addListener(startup);
browser.menus.onClicked.addListener(async function (e, tab) {
    if (e.menuItemId === "mark-page") {
        console.log("set mark-page", tab.id);
        await browser.storage.local.set({
            windows: tab.id,
        });
    }
});

var timeout;
var lastOrigin;

async function detectRequest(requestDetails) {
    let windowList = (await browser.storage.local.get("windows")).windows;
    if (!windowList || requestDetails.tabId !== windowList) return;
    if (
        requestDetails.originUrl === lastOrigin ||
        (!requestDetails.url.includes("glassdoor") &&
            !requestDetails.url.includes("linkedin"))
    ) {
        return;
    }
    console.log(`Mon: ${requestDetails.url}`);
    if (timeout) clearTimeout(timeout);
    timeout = setTimeout(() => {
        console.log("autoload detected");
        lastOrigin = requestDetails.originUrl;
        browser.tabs.sendMessage(windowList, { type: "AUTOLOAD_FINISHED" });
    }, 3000);
}

browser.webRequest.onBeforeRequest.addListener(detectRequest, {
    urls: ["<all_urls>"],
});
