try {
    chrome.runtime.setUninstallURL("https://whatso.net");
    var i = 0;
    var aaa = 0;
    var objectMake;
    var intervalInt = 0;
    var isPause = false;
    var isSameTab = false;
    chrome.storage.local.set({ "inNewTab": false });
    var messageIds = [];
    const sleep = m => new Promise(r => setTimeout(r, m))
    chrome.tabs.onActivated.addListener(activeInfo => move(activeInfo));
    chrome.tabs.onUpdated.addListener(async function(tabId, changeInfo, tab) {
        if (changeInfo.url == "chrome://newtab/") {
            isPause = false;
            isSameTab = false;
        }
        if (changeInfo.url == "https://web.whatsapp.com/") {
            isSameTab = true;
        }
    });

    async function move(activeInfo) {
        try {
            chrome.tabs.get(activeInfo.tabId, async(tab) => {
                if (tab.url == "https://web.whatsapp.com/") {
                    isSameTab = true;
                } else {
                    isSameTab = false;
                }
            });
        } catch (error) {
            if (error == 'Error: Tabs cannot be edited right now (user may be dragging a tab).') {
                setTimeout(() => move(activeInfo), 50);
            }
        }
    }
    chrome.runtime.onMessage.addListener(
        (request, sender, sendResponse) => {
            if (request.message === "sendmessage") {
                isPause = false;
                isSameTab = true;
                chrome.storage.local.set({ "inNewTab": false });
                Apisendmessage();
            }
            if (request.message === "closeNewTab") {
                chrome.storage.local.get("inNewTab", ({ inNewTab }) => {
                    chrome.storage.local.get("closeChromeTabId", async({ closeChromeTabId }) => {
                        if (inNewTab == true) {
                            const sleep = m => new Promise(r => setTimeout(r, m));
                            await sleep(5000);
                            isPause = false;
                            chrome.tabs.remove(closeChromeTabId, function() {});
                        }
                    });
                });
            }
        });

    chrome.alarms.onAlarm.addListener(a => {
        isSameTab = false;
        Apisendmessage();
    });

    chrome.runtime.onInstalled.addListener(() => {
        chrome.alarms.get('alarm', a => {
            if (!a) {
                chrome.alarms.create('alarm', { periodInMinutes: 1 });
            }
        });
        chrome.windows.getAll({ populate: true }, function(windows) {
            windows.forEach(function(window) {
                window.tabs.forEach(function(tab) {
                    //collect all of the urls here, I will just log them instead
                    if (tab.url == "https://web.whatsapp.com/") {
                        chrome.scripting.executeScript({
                            target: { tabId: tab.id },
                            function: () => {
                                window.location.reload();
                            }
                        });
                    }
                });
            });
        });
    });

    function Apisendmessage() {
        chrome.storage.local.get("emailId", ({ emailId }) => {
            chrome.storage.local.get("username", ({ username }) => {
                chrome.storage.local.get("password", ({ password }) => {
                    chrome.storage.local.get("fromNumber", ({ fromNumber }) => {
                        chrome.storage.local.get("isActivatedApi", async({ isActivatedApi }) => {
                            chrome.storage.local.get("isDeactivate", async({ isDeactivate }) => {
                                if (emailId && username && password && isActivatedApi && !isDeactivate) {
                                    const rawResponse = await fetch('https://webapi.whatso.net/api/UnAuthorized/get-whatsapp-messages', {
                                        method: 'POST',
                                        headers: {
                                            'Accept': 'application/json',
                                            'Content-Type': 'application/json'
                                        },
                                        body: JSON.stringify({
                                            "emailId": emailId,
                                            "key": username,
                                            "FromNumber": fromNumber,
                                            "secret": password,
                                            "apiMode": 2,
                                        })
                                    });
                                    const content = await rawResponse.json();
                                    var messages = content.data;
                                    chrome.storage.local.set({ "messagesApi": messages });
                                    if (!isPause && messages != null) {
                                        if (messages[i].toNumber != null && messages[i].messageText != null) {
                                            isPause = true;
                                            if (isSameTab == true) {
                                                await chrome.tabs.update({ active: true, url: "https://web.whatsapp.com/" });
                                            } else {
                                                await chrome.tabs.create({ url: "https://web.whatsapp.com/" });
                                                const sleep = m => new Promise(r => setTimeout(r, m));
                                                await sleep(5 * 1000);
                                            }
                                            setTimeout(function() {
                                                chrome.tabs.query({ active: true, lastFocusedWindow: true }, tabs => {
                                                    if (tabs.length > 0) {
                                                        let url = tabs[0].url;
                                                        if (url == "https://web.whatsapp.com/") {
                                                            chrome.runtime.sendMessage({ message: "closeNewTab" }, (response) => {});
                                                        }
                                                    }
                                                });
                                            }, 25 * 1000);
                                            chrome.windows.getCurrent(w => {
                                                chrome.tabs.query({ active: true, windowId: w.id }, tabs => {
                                                    const tabId = tabs[0].id;
                                                    chrome.storage.local.set({ "closeChromeTabId": tabId });
                                                    chrome.scripting.executeScript({
                                                        target: { tabId: tabId },
                                                        function: startFunction
                                                    });
                                                });
                                            });
                                        }
                                    }
                                }
                            });
                        });
                    });
                });
            });
        });
    }
    
    async function getCurrentTab() {
        let queryOptions = { active: true, currentWindow: true };
        let [tab] = await chrome.tabs.query(queryOptions);
        return tab;
    }
    async function showAlert() {
        if (document.getElementsByClassName("_2Zdgs")[0]) {
            document.getElementsByClassName("_2Zdgs")[0].click();
        } else {
            if (document.getElementsByClassName("_4sWnG").length > 0) {
                document.getElementsByClassName("_4sWnG")[0].click();
            }
        }
        return true;
    }
} catch {
    isPause = false;
}