/* You may find the license in the LICENSE file */

const EXPORTED_SYMBOLS = ['overrideUA', 'amendUA'];

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;
const Cu = Components.utils;
const Ctor = Components.Constructor;
const module = Cu.import;
const Exception = Components.Exception;

module('resource://dta/version.jsm');

function Manipulator() {
	this._m = {};
}
Manipulator.prototype = {
	register: function(id, matcher) {
		this._m[id] = {
				matcher: matcher,
				funcs: Array.map(arguments, function(e) e).slice(2)
		};	
	},
	unregister: function(id) {
		if (id in this._m) {
			delete this._m[id];
		}
	},
	modify: function(context, spec) {
		for each (let m in this._m) {
			if (m.matcher.test(spec)) {
				try {
					for each (let func in m.funcs) {
						func.apply(context);
					}
				}
				catch (ex) {
					Cu.reportError(ex);
				}
			}
		}		
	}
}

for each (let [m, sp] in [['URL', function(c) c.spec], ['Http', function(c) c.URI.spec]]) {
	let _m = new Manipulator();
	let _sp = sp;
	this['register' + m] = function() _m.register.apply(_m, arguments);
	this['unregister' + m] = function(id) _m.unregister(id);
	this['modify' + m] = function(context) _m.modify(context, _sp(context));
	EXPORTED_SYMBOLS.splice(EXPORTED_SYMBOLS.length, 3, 'register' + m, 'unregister' + m, 'modify' + m);
}

_uaextra = "DownThemAll!";
_uaplatform = (function() {
	let ph = Cc["@mozilla.org/network/protocol;1?name=http"].getService(Ci.nsIHttpProtocolHandler);
	return ph.platform + "; " + ph.oscpu + "; " + ph.language;
})();
_uaextrap = _uaextra + " (" + _uaplatform + "; like wget)";
Version.getInfo(function(v) {
	_uaextrap = _uaextra + "/" + v.BASE_VERSION + " (" + _uaplatform + "; 2.0; like wget)";
	_uaextra += "/" + v.BASE_VERSION;
});

function overrideUA() {
	this.setRequestHeader('User-Agent', _uaextrap, false);
}
function makeAnonymous() {
	try { this.referrer = null; } catch (ex) { /* no op */ }
	this.setRequestHeader('Referer', '', false);
	this.loadFlags |= Ci.nsIRequest.LOAD_ANONYMOUS;
	this.setRequestHeader('Cookie', '', false);
}

function amendUA() {
	let ua = this.getRequestHeader('User-Agent');
	if (!/^DownThemAll/.test(ua)) {
		this.setRequestHeader('User-Agent', ua + " " + _uaextra, false);
	}
}

// Sourceforge
registerHttp(
	'sourceforge.net',
	/(?:https?:\/\/|\.)(?:sf|sourceforge)\.net\//,
	overrideUA,
	makeAnonymous
);

// Rapidshare direct
registerURL(
	'rapidshare direct',
	/^https?:\/\/(?:[\w\d_.-]+\.)?rapidshare\.com\/files\/[^?]*?(?!\?directstart=1)$/,
	function() this.spec += "?directstart=1"
);