exports.main = function() {
    const privateBrowsing = require("sdk/private-browsing");
    const self = require("sdk/self");
    const notifications = require("sdk/notifications");
    const prefs = require('sdk/simple-prefs');
    const storage = require('sdk/simple-storage').storage;
    const config = require('sdk/preferences/service');
    const windows = require("sdk/windows").browserWindows;
    const panel = require("sdk/panel");
    const widget = require("sdk/widget")
    const {Cc, Ci} = require('chrome');
    
    const manualConfigNames = ["http", "http_port", "share_proxy_settings", "ssl", "ssl_port", "ftp", "ftp_port", "socks", "socks_port", "socks_version", "no_proxies_on"];
    
    function humanReadableProxySetting(number) {
        switch(number) {
            case 0:
                return "No Proxy";
            case 1:
                return "Manual";
            case 2:
                return "Automatic URL";
            case 4:
                return "Auto-detect";
            case 5:
                return "System Proxy";
            default:
                throw "no such proxy setting";
        }
    }
    
    function isInPrivateBrowsing() {
        let isPrivate = false;
        for each (let window in windows) {
            if (privateBrowsing.isPrivate(window)) {
                isPrivate = true;
                break;
            }
        }
        wdg.contentURL = self.data.url(isPrivate? "icon22.png": "icon22_off.png");
        wdg.tooltip = isPrivate? "Tor is ON": "Tor is OFF";
        pnl.contentURL= gettor()? self.data.url("panel.html"): self.data.url("paneloff.html");


        return isPrivate;
    }
    
    function getProxyType() {
        return config.get("network.proxy.type");
    }
    
    function setProxyType(type) {
        config.set("network.proxy.type", type);
    }
    
    function getManualConfig() {
        let conf = {};
        for (let i = 0;i < manualConfigNames.length;i++) {
            let c = manualConfigNames[i];
            conf[c] = config.get("network.proxy." + c);
        }
        return conf;
    }
    
    function setManualConfig(conf) {
        for (let c in conf) {
            config.set("network.proxy." + c, conf[c]);
        }
        notifications.notify({
            title: "Private Browsing Proxy",
            text: "Manual proxy settings changed",
            iconURL: self.data.url(isInPrivateBrowsing()? "icon64.png": "icon64_off.png")
        });
    }
    
    function getURLConfig() {
        return config.get("network.proxy.autoconfig_url");
    }
    
    function setURLConfig(url) {
        config.set("network.proxy.autoconfig_url", url);
        notifications.notify({
            title: "Private Browsing Proxy",
            text: "Auto-URL setting changed to " + url,
            iconURL: self.data.url(isInPrivateBrowsing()? "icon64.png": "icon64_off.png")
        });
    }
	
	function getHomepage() {
		return config.get("browser.startup.homepage");
	}
	
	function setHomepage(url) {
		config.set("browser.startup.homepage", url);
	}
    
    function assess() {
        let inPB = isInPrivateBrowsing();
        if (inPB != storage["lastDetectedPBState"]) {
            storage["lastDetectedPBState"] = inPB;
			if (prefs.prefs["privateHomepage"] != "") {
				if (inPB) {
					storage["userHomepage"] = getHomepage();
					setHomepage(prefs.prefs["privateHomepage"]);
				} else {
					setHomepage(storage["userHomepage"]);
				}
			}
            if (prefs.prefs["switchToAltProfileOnly"] && [1, 2].indexOf(getProxyType()) != -1) {
                if (inPB) {
                    if (getProxyType() == 1) {
                        storage["userManualConfig"] = getManualConfig();
                        setManualConfig(storage["PBPManualConfig"]);
                    } else {
                        storage["userURLConfig"] = getURLConfig();
                        setURLConfig(storage["PBPURLConfig"]);
                    }
                } else {
                    if (getProxyType() == 1) {
                        setManualConfig(storage["userManualConfig"]);
                    } else {
                        setURLConfig(storage["userURLConfig"]);
                    }
                }
            } else {
                if (inPB) {
                    storage["userProxyConfig"] = getProxyType();
                    setProxyType(prefs.prefs["desiredProxyConfig"]);
                } else {
                    setProxyType(storage["userProxyConfig"]);
                }
            }
        }
    }

    function settor(){
    config.set("network.proxy.socks", "127.0.0.1");
    config.set("network.proxy.socks_port", 9050);
    config.set("network.proxy.socks_version", 5);
    config.set("network.proxy.socks_remote_dns", true);
    }

    function gettor(){
    settor();
    if (config.get("network.proxy.type")=="1")
      if (config.get("network.proxy.socks")=="127.0.0.1")
        if (config.get("network.proxy.socks_port")=="9050")
          if (config.get("network.proxy.socks_version")=="5")
            if (config.get("network.proxy.socks_remote_dns")==true)
              return true;
    return false;
    }

    function proxytext(){
    if (gettor())
      return "Using Tor proxy at " + config.get("network.proxy.socks") + ":" + config.get("network.proxy.socks_port");
    return "Proxy changed to " + humanReadableProxySetting(config.get("network.proxy.type"));
    }


    function proxyPrefListener(callback) {
        this.branch = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch("network.proxy.type");
		this.callback = callback;
		this.observe = function(subject, topic, data) {
			if (topic == 'nsPref:changed') {
				this.callback();
			}
		};
		this.branch.addObserver("", this, false);
	}
	new proxyPrefListener(function() {
        notifications.notify({
            title: "Private Browsing Proxy",
            text: proxytext(),
            iconURL: self.data.url(isInPrivateBrowsing()? "icon64.png": "icon64_off.png")
        });
	});
    
    let pnl = panel.Panel({
        contentURL: gettor()? self.data.url("panel.html"): self.data.url("paneloff.html"),
        contentScriptFile: self.data.url("panel.js")
    });
    
    pnl.port.on("responseManualConfig", function(conf) {
        storage["PBPManualConfig"] = conf;
        pnl.port.emit("offerManualConfig", conf);
    });
    pnl.port.on("responseURLConfig", function(url) {
        storage["PBPURLConfig"] = url;
        pnl.port.emit("offerURLConfig", url);
    });
    pnl.port.on("responseSize", function(size) {
        pnl.resize(size.width, size.height);
    });
    pnl.on('show', function() {
        pnl.port.emit("requestSize");
    });
    let wdg = widget.Widget({
        id: "private-browsing-proxy",
        label: "Tor is OFF",
        contentURL: self.data.url("icon22.png"),
        panel: pnl
    });
    
    if (!storage["userManualConfig"]) {
        storage["userManualConfig"] = getManualConfig();
    }
    if (!storage["PBPManualConfig"]) {
        pnl.port.emit("requestManualConfig");
    } else {
        pnl.port.emit("offerManualConfig", storage["PBPManualConfig"]);
    }
    if (!storage["userURLConfig"]) {
        storage["userURLConfig"] = getURLConfig();
    }
    if (!storage["PBPURLConfig"]) {
        pnl.port.emit("requestURLConfig");
    } else {
        pnl.port.emit("offerURLConfig", storage["PBPURLConfig"]);
    }
    if (!storage["lastDetectedPBState"]) {
        storage["lastDetectedPBState"] = isInPrivateBrowsing();
    }
    if (!storage["userProxyConfig"]) {
        storage["userProxyConfig"] = getProxyType();
    }
	if (!storage["userHomepage"]) {
        storage["userHomepage"] = getHomepage();
    }
    
    assess();
    windows.on('open', assess);
    windows.on('close', assess);
}
