let host = "ws://127.0.0.1:9393";

var websocket;

// Sendet Nachricht an C#
function SendMessage(_id, _text) {
    console.log(_text);

    if (_text == null) {
        _text = ["undefined"];
    }

    var toSend = { Id: _id, ResultText: _text };
    console.log(toSend);

    websocket.send(JSON.stringify(toSend));
}

let connected = false;

// Zeigt das grüne Icon
function SetConnected() {
    connected = true;
    chrome.browserAction.setIcon({ path: { '19': "/icons/Green19.png" } });
}

// Zeigt das rote Icon
function SetDisconnected() {
    connected = false;
    chrome.browserAction.setIcon({ path: { '19': "/icons/Red19.png" } });
}

function createWebSocketConnection() {

    if (connected) return;

    SetDisconnected();
    if ('WebSocket' in window) {
        websocket = new WebSocket(host);
        console.log("======== websocket ===========", websocket);

        websocket.onopen = function () {
            SetConnected();
        };

        websocket.onmessage = function (event) {
            var received_msg = JSON.parse(event.data);

            console.log(event.data);
            console.log(received_msg);

            if (received_msg.Type === "ExecuteJavaScript") {
                ExecuteJavaScript(received_msg.Code, (res) => {
                    SendMessage(received_msg.Id, res);
                });
            } else if (received_msg.Type === "SetUrl") {
                SetUrl(received_msg.Url, () => {
                    SendMessage(received_msg.Id, "updated");
                });
            } else if (received_msg.Type === "GetUrl") {
                GetUrl((url) => {
                    SendMessage(received_msg.Id, url);
                });
            } else if (received_msg.Type === "SpoofUserAgent") {
                if (received_msg.Activated) {
                    doMobileSearches = true;
                    MobileSpoofedAgent = received_msg.UserAgent;
                    SendMessage(received_msg.Id, "true");
                } else {
                    doMobileSearches = false;
                    SendMessage(received_msg.Id, "false");
                }
            }
            else if (received_msg.Type === "ResetBrowser") {
                ClearAllCookies(() => {
                    ClearLocalStorage(() => {
                        SendMessage(received_msg.Id, "true");
                    });
                });
            }
        };

        websocket.onclose = function () {
            SetDisconnected();
        };
    }
}
// createWebSocketConnection();

// JS Code ausführen
function ExecuteJavaScript(code, callback) {
    chrome.tabs.executeScript(null, { code: '{' + code + '}', runAt: 'document_start' }, (rec) => {
        callback(rec);
    });
}

function ClearAllCookies(callback) {
    chrome.cookies.getAll({}, function (cookies) {
        for (var i = 0; i < cookies.length; i++) {
            let cookie = cookies[i];
            chrome.cookies.remove({ url: `http${cookie.secure ? 's' : ''}://` + cookie.domain + cookie.path, name: cookie.name });
        }
    });
    callback();
}

function ClearLocalStorage(callback) {
    chrome.storage.sync.clear(() => {
        callback();
    });
}

// Tab URL aktualisieren
function SetUrl(targetURL, callback) {
    chrome.tabs.update(null, { url: targetURL, active: true }, (tab) => {
        callback();
    });
}

// Aktuelle URL des aktuellen Tabs laden
function GetUrl(callback) {
    chrome.tabs.getSelected(null, function (tab) {
        var tablink = tab.url;
        callback(tablink);
    });
}

// Klick auf das Icon
// chrome.browserAction.onClicked.addListener(function (activeTab) {
//     //chrome.tabs.executeScript(null, {code: '{ AddYouTubeButton(); }', runAt: 'document_start'});
//     setTimeout(function () { createWebSocketConnection(); }, 100);
//     try { websocket.close(); } catch { }
// });
setInterval(function () { createWebSocketConnection(); }, 1500);

doMobileSearches = false;
MobileSpoofedAgent = "";
chrome.webRequest.onBeforeSendHeaders.addListener(details => {
    const { requestHeaders } = details;
    // requestHeaders.forEach(header => {
    //     if (header.name === 'User-Agent') {
    //         if (doMobileSearches) header.value = MobileSpoofedAgent;
    //         else header.value = navigator.userAgent;
    //     }
    // });


    if (doMobileSearches) {
        requestHeaders.push({ "name": "User-Agent", "value": MobileSpoofedAgent });
    }
    else {
        requestHeaders.push({ "name": "User-Agent", "value": navigator.userAgent });
    }

    return { requestHeaders };
}, {
    urls: ['https://*.bing.com/*', 'https://www.httpbin.org/headers'],
}, ['blocking', 'requestHeaders']);
