'use strict';

var browser = browser || chrome
var ua = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)";
var targetPage = "*://*/*";
var extension_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 updateIcon() {
  browser.storage.sync.get('extension_status', function(data) {
    extension_status = data.extension_status;

    browser.browserAction.setIcon({path: 'icon' + extension_status + '.png'});
    extension_status++;
    if (extension_status > 1){
        extension_status = 0;
    }
    browser.storage.sync.set({extension_status: extension_status}, function() {
      console.log('The extension_status is set to ' + extension_status);
    });
  });
};




browser.browserAction.onClicked.addListener(updateIcon);
//updateIcon();
//
//var ua = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)";
var targetPage = "*://*/*";

/*
Rewrite the User-Agent header to "ua".
*/
function rewriteUserAgentHeader(e) {

  browser.storage.sync.get('extension_status', function(data) {
    extension_status = data.extension_status;
    console.log('Browser http request:  ' + extension_status);

  });
    console.log(extension_status);
   if(extension_status == 0){
    return {requestHeaders: e.requestHeaders};
   }


    for (var header of e.requestHeaders) {
        if (header.name.toLowerCase() === "user-agent") {
            header.value = ua;
        }
      }
    return {requestHeaders: e.requestHeaders};

}

/*
Add rewriteUserAgentHeader as a listener to onBeforeSendHeaders,
only for the target page.

Make it "blocking" so we can modify the headers.
*/
browser.webRequest.onBeforeSendHeaders.addListener(rewriteUserAgentHeader,
                                          {urls: [targetPage]},
                                          ["blocking", "requestHeaders"]);

