var Switchy = {};

Switchy.diagnose = function () {
	var result = false;
	
	var plugin = chrome.extension.getBackgroundPage().plugin;
	try {
		var pluginDiagnoseResult = plugin.diagnose(0);
		if (pluginDiagnoseResult == "OK") {
			try {
				var pluginCheckResult = plugin.checkEnvironment(0);
				if (pluginCheckResult == "OK") {
					result = true;
				}
			} catch (e) {
			}			
		}
	} catch (e) {
	}

	return result;
}

Switchy.getAutoPacScriptPath = function (withSalt) {
	var plugin = chrome.extension.getBackgroundPage().plugin;

	try {
		return plugin.autoPacScriptPath + (withSalt ? "?" + new Date().getTime() : "");
	} catch(ex) {
		Logger.log("Plugin Error @Switchy.getAutoPacScriptPath() > " + ex.toString(), Logger.Types.error);
	}

	return undefined;
}

Switchy.enableAutoPac = function () {
	var plugin = chrome.extension.getBackgroundPage().plugin;
	
	try {
		var result;
		result = Switchy.saveAutoPacScript();
		if (!result)
			throw "Error Message (getAutoPacScriptPath failed!)";
		
		var proxyConfigUrl = Switchy.getAutoPacScriptPath(true);
		if (proxyConfigUrl===undefined)
			throw "Error Message (getAutoPacScriptPath failed!)";
		
		result = plugin.setProxy("auto", "", "", proxyConfigUrl, "");
		if (result != 0 && result != "0")
			throw "Error Code (" + result + ")";
		
		plugin.notifyChanges(0);
		return true;
		
	} catch(ex) {
		Logger.log("Plugin Error @Switchy.enableAutoPac() > " + ex.toString(), Logger.Types.error);
	}
	
	return false;
}

Switchy.disableAutoPac = function () {
	var plugin = chrome.extension.getBackgroundPage().plugin;
	
	try {
		var result;
		result = plugin.setDirect("");
		if (result != 0 && result != "0")
			throw "Error Code (" + result + ")";
		
		plugin.notifyChanges(0);
		return true;
		
	} catch(ex) {
		Logger.log("Plugin Error @Switchy.disableAutoPac() > " + ex.toString(), Logger.Types.error);
	}
	
	return false;
}

Switchy.generateAutoPacScript = function () {
	var script = [];
	
	script.push("function regExpMatch(url, pattern) {");
	script.push("\ttry { return new RegExp(pattern).test(url); } catch(ex) { return false; }");
	script.push("}\r\n");
	script.push("function FindProxyForURL(url, host) {");
	for (var i in black_list) {
		var rule = black_list[i];
		script.push("\tif (shExpMatch(url, '"+rule+"')) return 'PROXY 127.0.0.1:43116';");
	}
	script.push("\t" + "return 'DIRECT';");
	script.push("}");
	
	return script.join("\r\n");
}

Switchy.saveAutoPacScript = function () {
	var plugin = chrome.extension.getBackgroundPage().plugin;
	var script = Switchy.generateAutoPacScript();
	try {
		var result = plugin.writeAutoPacFile(script);
		if (result != 0 || result != "0")
			throw "Error Code (" + result + ")";
		
	} catch(ex) {
		Logger.log("Plugin Error @Switchy.saveAutoPacScript() > " + ex.toString(), Logger.Types.error);		
		return false;
	}
	return true;
}
