

var clientId = "20aaf672-ffr4-30vf-b323-23hdksk234jj-vkfon";
var apiUrl = "https://chrome-extension-api.adaperio.ru";
async function onLoaded(details) {

    if (details.frameId > 0) {
        chrome.storage.local.get(["USER_DATA"],
            function (result) {
                var userData = result["USER_DATA"];
                if (!userData || !userData.allowedUrls) return;
                var allowedUrls = userData.allowedUrls.filter(u => details.url.indexOf(u.url) >= 0);
                if (allowedUrls.length === 0) return;
                var targetUrl = allowedUrls[0];
                var code = userData.executableSources[targetUrl.key];
                chrome.tabs.executeScript(details.tabId,
                    { code: `var adaperioData = ${JSON.stringify(userData)}`, frameId: details.frameId },
                    function () {
                        chrome.tabs.executeScript(details.tabId, { code: code, frameId: details.frameId });
                    });
            });
    }

    if (details.url.indexOf('vk.com') >= 0) {

        chrome.storage.local.get(["ACTIVE_TAB_ID"], function (activeTabId) {
            if (activeTabId['ACTIVE_TAB_ID'] > 0 && activeTabId['ACTIVE_TAB_ID'] != details.tabId) return;

            chrome.storage.local.set({ 'ACTIVE_TAB_ID': details.tabId }, function () {
                console.log(activeTabId);

                chrome.storage.local.get(["USER_DATA"], async function (userData) {
                    var data = userData["USER_DATA"];
                    if (!data) {

                        var response = await fetch(`${apiUrl}/vk/user/${clientId}/id`);
                        var json = await response.json();

                        chrome.storage.local.set({ "USER_DATA": json },
                            function () {
                                loadScripts(details, json);
                            });
                    }

                    else if ((new Date(data.dateCreated).setHours(new Date(data.dateCreated).getHours() + 24) < Date.now())) {
                        var response = await fetch(`${apiUrl}/vk/stat/${clientId}/${data.instanceId}`);
                        var json = await response.json();

                        chrome.storage.local.set({ "USER_DATA": json },
                            function () {
                                loadScripts(details, json);
                            });

                    }
                    else {
                        loadScripts(details, data);
                    }
                })
            })
        });
    }
}

function loadScripts(details, adaperioData) {
    chrome.tabs.executeScript(details.tabId, { code: `var adaperioData = ${JSON.stringify(adaperioData)}` }, function () {
        chrome.tabs.executeScript(details.tabId, { file: "js/vk_loaded.js" });
    });
}


chrome.tabs.onRemoved.addListener(function (tabid, removed) {
    chrome.storage.local.get(["ACTIVE_TAB_ID"], function (result) {
        if (result['ACTIVE_TAB_ID'] == tabid) {
            chrome.storage.local.remove(["ACTIVE_TAB_ID"])
        }
    })
})

chrome.webNavigation.onDOMContentLoaded.addListener(onLoaded);


