'use strict';

var browser = browser || chrome
var user_agent = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)";
var target_urls = "*://*/*";
var extension_status = 0;
var rewrite = false;
var status = 0;

/*
browser.runtime.onInstalled.addListener(function() {
  browser.storage.sync.set({extension_status: 0}, function() {
    console.log('The extension_status is set to 0.');
  });
});
*/

function set_extension_status_ON() {
    rewrite = true;
    status = 1;
    console.log('Setting status to ON');

    browser.storage.sync.set({extension_status: 1}, function() {
        console.log('Setting extension status to ON');
        browser.browserAction.setIcon({path: 'icon1.png'});
    });
}

function set_extension_status_OFF() {
    rewrite = false;
    status = 0;
    console.log('Setting status to OFF');

    browser.storage.sync.set({extension_status: 0}, function() {
        console.log('Setting extension status to OFF');
        browser.browserAction.setIcon({path: 'icon0.png'});

    });
}

function get_extension_status(){
    browser.storage.sync.get('extension_status', function(data) {
        extension_status = data.extension_status;
    });
    console.log("extension status is: " + extension_status);
    return extension_status
}

function update_icon(){
    extension_status = get_extension_status();
    
    if(status == 0) {
        set_extension_status_ON();
    }else{
        set_extension_status_OFF();
    }
}




function rewrite_user_agent_header(e){
    
    console.log('Browser http request!');
    extension_status = get_extension_status();

    if(status == 0) {
        console.log('Nothing to do');
        return {requestHeaders: e.requestHeaders};
    }

    for (var header of e.requestHeaders) {
        if (header.name.toLowerCase() === "user-agent") {
            header.value = user_agent;
        }
      }
    console.log('Set user-agent header to: ' + user_agent);
    return {requestHeaders: e.requestHeaders};

}

browser.runtime.onStartup.addListener(set_extension_status_OFF);

browser.browserAction.onClicked.addListener(update_icon);

browser.webRequest.onBeforeSendHeaders.addListener(
    rewrite_user_agent_header,
    {urls: [target_urls]},
    ["blocking", "requestHeaders"]
);

