/**
 * GNU LibreJS - A browser add-on to block nonfree nontrivial JavaScript.
 * *
 * Copyright (C) 2011, 2012 Loic J. Duros
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see  <http://www.gnu.org/licenses/>.
 *
 */

// change following to start debugging, or do it from about:config
// change value to "all" to get all the console.logs.
var name = "extensions.jid1-KtlZuoiikVfFew.sdk.console.logLevel";
require("sdk/preferences/service").set(name, "off");

const jsAnalyzer = require("js_checker/js_checker");

const widgets = require("sdk/widget");
const panel = require("sdk/panel");

const pageWorker = require("sdk/page-worker");

const jsLoadObserver = require("js_load_observer/js_load_observer");

const data = require("sdk/self").data;
const httpObserver = require("http_observer/http_request_observer");

const { Cc, Ci } = require("chrome");
const { getMostRecentBrowserWindow } = require('sdk/window/utils'); 
const jetpackID = require("self").id; 

const tabs = require("sdk/tabs");
//const prefs = require("preferences/preferences");
const simpleStorage = require("sdk/simple-storage");
const addonManage = require("addon_management/install_uninstall");
const removedScripts = require("script_entries/removed_scripts").removedScripts;
const acceptedScripts = require("script_entries/accepted_scripts").acceptedScripts;


// manage preference whitelist.
const prefChange = require("addon_management/prefchange");
// set whitelist at startup.
prefChange.init();

var allowedRef = require("http_observer/allowed_referrers").allowedReferrers;

var urlHandler = require("url_handler/url_handler");

var widgetIsOn = false;

var uiInfo = require("ui/ui_info");
var scriptPanel = require("ui/script_panel.js");

var panelContent = function () {

  let panel = this;
  var message, externalEntries, 
      externalScripts, urlTabIndex, tabData;

  tabs.activeTab.attach({
    contentScriptFile: [data.url('third_party/jquery-src.js'),
                        data.url('script_detector/script_detector.js')],
    contentScriptWhen: 'ready',

	  onMessage: function (respData) {
	    // complain content script


      var url = urlHandler.removeFragment(tabs.activeTab.url);
      var acceptedScriptEntries = respData['value']['accepted'];
      var removedScriptEntries = respData['value']['blocked'];
      var i, script;

      for (i = 0; i < acceptedScriptEntries.length; i++) {
        if (acceptedScriptEntries[i].inline === false) {
          script = acceptedScripts.returnWhenFound(url, {inline: false, contents: acceptedScriptEntries[i].url});
          if (script) {
            acceptedScriptEntries[i].reason = script.reason;
          }
        }
      }

      for (i = 0; i < removedScriptEntries.length; i++) {
        script = removedScripts.returnWhenFound(url, {inline: false, contents: removedScriptEntries[i].url});
        if (script) {
          removedScriptEntries[i].reason = script.reason;
        }
      }

	    panel.postMessage({'pageURL': url, 
                         'urlData': scriptPanel.addScriptsToPanelList(tabs.activeTab.url, respData),
                         'isAllowed': allowedRef.urlInAllowedReferrers(url)});
	  }
    
    
  });




};

// page mod was here.


var removePanelContent = function () {
  this.postMessage('hide');
};

exports.main = function(options, callbacks) {
  if (options.loadReason === 'enable' || 
	    options.loadReason === 'install') {
	  addonManage.onLoad();
  }
};

var mainPanel = panel.Panel({
  contentURL: data.url('display_panel/content/display-panel.html'),
  width:  800,
  height: 500,
  contentScriptFile: [data.url('third_party/jquery-src.js'), data.url('display_panel/main_panel.js')],
  onShow: panelContent,
  onHide: removePanelContent
});

var widget = widgets.Widget({
  id: 'librejs-toggle-switch',
  label: 'LibreJS',
  contentURL: data.url('widget/images/librejs.png'),
  contentScriptWhen: 'end',
  contentScriptFile: [data.url('widget/widget.js')],
  panel:mainPanel
});


var getWidgetElem = function () {
  let { document } = getMostRecentBrowserWindow(); 
  var name = "widget:" + jetpackID + '-librejs-toggle-switch';
  var widgetElem = document.getElementById(name);
  return widgetElem;
};

widget.port.on('left-click', function () {
  if (mainPanel.isShowing) {
    mainPanel.hide();
  } else {
    mainPanel.show();
  }
});

mainPanel.port.on('complainButtonClicked', function () {
  mainPanel.hide();
});

mainPanel.port.on('allowAllClicked', function (url) {
  url = urlHandler.removeFragment(url);
  allowedRef.addPage(url);
  tabs.activeTab.reload();
});

mainPanel.port.on('disallowAllClicked', function (url) {
  //console.log('url is', url);
  url = urlHandler.removeFragment(url);
  //console.log('before clear, url is in allowedRef', allowedRef.urlInAllowedReferrers(url));
  allowedRef.clearSinglePageEntry(url);
  //console.log('after clear, url is in allowedRef', allowedRef.urlInAllowedReferrers(url));
  mainPanel.hide();
  tabs.activeTab.reload(); 
});

mainPanel.port.on('openInTab', function (text) {
  var str = generateDataURI(text);
  tabs.open(str);
});

var generateDataURI = function (encodedText) {
  return "data:text/html;charset=UTF-8;base64," + encodedText;
}

exports.onUnload = addonManage.onUnload;
exports.onLoad = addonManage.onLoad;
