/**
 * 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/>.
 *
 */

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

const widgets = require("widget");
const panels = require("panel");
const pageWorker = require("page-worker");

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

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

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


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

// script list for those 
var scriptList = require("ui/script_list");
var panelRemovedScripts = scriptList.rejectedScriptsList;
var panelAcceptedScripts = scriptList.acceptedScriptsList; 


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

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

var widgetIsOn = false;

var uiInfo = require("ui/ui_info");

// remove script entries from tabs
// that are closed.
uiInfo.clearScriptsFromClosedTab();

var panelContent = function () {

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

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

	onMessage: function (respData) {
	    // complain content script
	    if (typeof data === 'object') { 
		handleTabResponse(panel, respData);
	    } else {
		panel.postMessage(respData);
	    }
	}
    });


    url = urlHandler.removeFragment(tabs.activeTab.url);
    
    // contains external scripts removed at download time.
    urlData = removedScripts.getScripts(url);

    // contains all the other scripts (that used domHandler).
    tabData = { 
	'removed': panelRemovedScripts[url],
	'accepted': panelAcceptedScripts[url]
    };

    if (urlData) {
	tabData.removed.concat(urlData);
    }

    message = {'urlData': tabData, 
	       'pageURL': url,
	       'isAllowed': allowedRef.urlInAllowedReferrers(url)};
    this.postMessage(message);
};

// 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 = panels.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',
    panel: mainPanel,
    contentURL: data.url('widget/images/librejs.png'),
    contentScriptWhen: 'end',
    contentScriptFile: data.url('widget/widget.js')
});


/*widget.port.on('right-click', function() {
    prefs.prefpanel.show();
});*/


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

mainPanel.port.on('allowAllClicked', function (url) {
    url = urlHandler.removeFragment(url);
    allowedRef.addPage(url);
    panelRemovedScripts[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));
    panelRemovedScripts[url] = [];
    mainPanel.hide();
    tabs.activeTab.reload(); 
});


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