/* Module for user preference operation. 
   Created by Zoominla, 09-11-2009         
*/

if(typeof(SETTINGS_INCLUDE) != "boolean") {
SETTINGS_INCLUDE = true;

const ObjectsUpdateConfig = [{"id":"scf_good_path", "default":"", "key":"uiSourceFileDirGood", "type":"textbox"},
							 {"id":"scf_bad_path", "default":"", "key":"uiSourceFileDirBad", "type":"textbox"},
							 {"id":"setDualTrack", "default":0, "key":"uiEnableDualTrack", "type":"select"}];
var ObjectsSaveConfig ={};

var configWrapper = null;

function PrefsWrapper(aRoot)
{
  const CI = Components.interfaces;
  const CC = Components.classes;
  const IID_Prefs = "@mozilla.org/preferences-service;1";
  this.prefSvc = CC[IID_Prefs].getService(CI.nsIPrefService);
  if(aRoot && typeof(aRoot) == "string") {
    this.branch = this.prefSvc.getBranch(aRoot);
  } else {
	this.branch = CC[IID_Prefs].getService(CI.nsIPrefBranch);
  }

  // "inherit" from nsIPrefBranch, re-assembling __proto__ chain as follows:
  //    this, nsIPrefBranch, PrefsWrapper1.prototype, Object.prototype
  this.branch.__proto__ = PrefsWrapper.prototype;
  this.__proto__ = this.branch;

  // Create "get*PrefDef" methods, which return specified default value
  // when an exception occurs - similar to nsPreferences.
  if(!("getIntPrefDef" in PrefsWrapper.prototype)) {
    var types = ["Int", "Char", "Bool", "Unichar", "File"];
    for(var i in types) {
      PrefsWrapper.prototype["get" + types[i] + "PrefDef"] = new Function(
        "aPrefName", "aDefValue",
          "try { return this.get" + types[i] + "Pref(aPrefName);\n" + 
          "} catch(e) {} return aDefValue;");
    }
  }
}

PrefsWrapper.prototype = {
  getSubBranch: function(aSubpath) {
    return new PrefsWrapper(this.branch.root + aSubpath);
  },

  // unicode strings
  getUnicharPref: function(aPrefName) {
    return this.branch.getComplexValue(aPrefName, 
      Components.interfaces.nsISupportsString).data;
  },
  setUnicharPref: function(aPrefName, aValue) {
    var str = Components.classes["@mozilla.org/supports-string;1"]
      .createInstance(Components.interfaces.nsISupportsString);
    str.data = aValue;
    this.branch.setComplexValue(aPrefName, 
      Components.interfaces.nsISupportsString, str);
  },

  // for strings with default value stored in locale's .properties file
  getLocalizedUnicharPref: function(aPrefName) {
    return this.branch.getComplexValue(aPrefName,
      Components.interfaces.nsIPrefLocalizedString).data;
  },

  // store nsILocalFile in prefs
  setFilePref: function(aPrefName, aValue) {
    this.branch.setComplexValue(aPrefName, Components.interfaces.nsILocalFile, 
      aValue);
  },
  getFilePref: function(aPrefName) {
    return this.branch.getComplexValue(aPrefName, 
      Components.interfaces.nsILocalFile);
  },

  // aRelTo - relative to what directory (f.e. "ProfD")
  setRelFilePref: function(aPrefName, aValue, aRelTo) {
    var relFile = Components.classes["@mozilla.org/pref-relativefile;1"]
      .createInstance(Components.interfaces.nsIRelativeFilePref);
    relFile.relativeToKey = aRelTo;
    relFile.file = aValue;
    this.branch.setComplexValue(aPrefName, 
      Components.interfaces.nsIRelativeFilePref, relFile);
  },
  getRelFilePref: function(aPrefName) {
    return this.branch.getComplexValue(aPrefName, 
      Components.interfaces.nsIRelativeFilePref).file;
  },

  // don't throw an exception if the pref doesn't have a user value
  clearUserPrefSafe: function(aPrefName) {
    try {
      this.branch.clearUserPref(aPrefName);
    } catch(e) {
	  dumpErr(e);
	}
  }
}

function queryRestart()
{
  var restartTips = getLocalString("tips.effect.restart");
  if(ask(restartTips, document.title)) {
	restartApp();
  }
}

function setLang(lang)   //language select
{
  try {
	 var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
		prefs.setCharPref("general.useragent.locale", lang);
	  queryRestart();
  }
  catch ( err ) {
	dumpErr( "SelectLanguage - " + err);
  }
}

function selectSkin(skinName)
{
  try {
	var skinDir = Io.getSpecialDir("globalskin", "AChrom");;
	if(!skinDir || !skinDir.exists()) return;
	skinDir.append(skinName+".jar");
	if(!skinDir || !skinDir.exists()) return;
	// Modify chrome.manifest file
	var manifestFile = Io.getSpecialDir(null, "AChrom");
	manifestFile.append("chrome.manifest");
	if(!manifestFile || !manifestFile.exists()) return;
	var manifestContent = "content transerver jar:transerver.jar!/content/transerver/\r\n \
locale transerver en-US jar:transerver.jar!/locale/en-US/\r\n \
locale transerver zh-CN jar:transerver.jar!/locale/zh-CN/\r\n \
skin transerver classic/1.0 jar:transerver.jar!/skin/\r\n \
skin xa	 Foxdie jar:globalskin/foxdie.jar!/xa/\r\n \
skin xt	 Foxdie jar:globalskin/foxdie.jar!/xt/\r\n"
	if(skinName == "foxdie") {
	  manifestContent += "skin global classic/1.0 jar:globalskin/foxdie.jar!/win/global/";
	} else {
	  manifestContent += "skin global classic/1.0 jar:globalskin/"+skinName+".jar!/";
	}
	Io.saveUTF8File(manifestContent, manifestFile, true);
	queryRestart();
  } catch ( err ) {
	dumpErr( "SelectSkin - " + err);
  }
}

function setAutoDel(e)
{
  isTaskAutoRemove = (e == "true" )? 1:0;
  //alert(e + " --" + isTaskAutoRemove);
}

function setTogetherNum(e)
{
  //post
  //if false set the number back
  	var xParam = new xmlrpcval({"id":new xmlrpcval(0, "string"),
							    "number":new xmlrpcval(e, "string")},
							    "struct");
	var request = new xmlrpcmsg("ts.node.setActNum", [xParam]);
	var payload = request.serialize("utf-8");
	var isOk = false;
	try{
		var resXml = SendRequstToServer(payload);
		if(resXml)
		{
		  var resData = parseRPC(resXml);
		  if(resData["result"] == "success")
		  {
			isOk = true;
		  }
		}
	}
	catch(e){}
	GetResponseFromServer2("set", "key=nodeActiveWorkerNum&value="+e, false);
	if(isOk)
	{
	  tongetherNumeber = parseInt(e);
	}
	else
	{
	  this.selectedIndex = tongetherNumeber - 1;
	}
}

function setRemoteMaster(e)
{
  GetResponseFromServer2("set", "key=uiBindAddrAny&value="+e, false);
  alert(getLocalString("config.set.responce"));
}

function RpcConfigValueChange(key, value)
{
  var xParam = new xmlrpcval({"key":new xmlrpcval(key, "string"),
								"value":new xmlrpcval(value, "string")},							   
								"struct");
	var request = new xmlrpcmsg("ts.config.valueChange", [xParam]);
	var payload = request.serialize("utf-8");
	 try{
		var resXml = SendRequstToServer(payload);
		if(resXml)
		{
		  var resData = parseRPC(resXml);
		  if(resData["result"] == "success")
		  {}
		}
	 } catch(e){
	  dumpErr(e);
	 }
}

function setDualTrack(e)
{
  RpcConfigValueChange("uiEnableDualTrack", e);
  GetResponseFromServer2("set", "key=uiEnableDualTrack&value="+e, false);
}

function setUseSingleCore(e)
{
  var xParam = new xmlrpcval({"id":new xmlrpcval(0, "string"),
							    "value":new xmlrpcval(e, "string")},
							    "struct");
  var request = new xmlrpcmsg("ts.node.setEncoderSingleCore", [xParam]);
  var payload = request.serialize("utf-8");
  var isOk = false;
  try{
	  var resXml = SendRequstToServer(payload);
	  if(resXml)
	  {
		var resData = parseRPC(resXml);
		if(resData["result"] == "success")
		{
		  isOk = true;
		}
	  }
	}
	catch(e){}
  GetResponseFromServer2("set", "key=uiEncodeSingleCore&value="+e, false);
}

function onSrcFileMoveDirChange(elem)
{
  if(!elem) return;
  var txtId = elem.id;
  var key = null;
  switch(txtId) {
	case "scf_good_path":
	  GetResponseFromServer2("set", "key=uiSourceFileDirGood&value="+elem.value, false);
	  key = "uiSourceFileDirGood";
	  break;
	case "scf_bad_path":
	  GetResponseFromServer2("set", "key=uiSourceFileDirBad&value="+elem.value, false);
	  key = "uiSourceFileDirBad";
	  break;
  }
  if(key) {
	RpcConfigValueChange(key, elem.value);
  }
}

function setSrcFileMoveDir(id)
{
  var txtBox = $e(id);
  if(!txtBox) return;
  var dir = Io.openDir('Select');
  if(dir){
	txtBox.value = dir.path;
  }
  onSrcFileMoveDirChange(txtBox);
}

function configUpdate()
{
  var actnum = GetResponseFromServer2("get", "key=nodeActiveWorkerNum", false);
  var isremote = GetResponseFromServer2("get", "key=uiBindAddrAny", false);
  var isSingleCore = GetResponseFromServer2("get", "key=uiEncodeSingleCore", false);
  if ($e("setUseSingleCore")) $e("setUseSingleCore").selectedIndex = isSingleCore ? parseInt(isSingleCore) : 0;
  if ($e("setRemoteMaster")) $e("setRemoteMaster").selectedIndex = isremote ? parseInt(isremote) : 0;
  tongetherNumeber = actnum ? parseInt(actnum) : 1;
  if ($e("setTogetherNumber")) $e("setTogetherNumber").selectedIndex = (tongetherNumeber - 1) >= 0 ? (tongetherNumeber - 1) : 0;
  for(var i=0;i<ObjectsUpdateConfig.length;++i)
  {
	var obj = ObjectsUpdateConfig[i];
	switch(obj['type'])
	{
	  case "textbox":
		if ($e(obj['id'])) {
			  var val = GetResponseFromServer2("get", "key="+obj['key'], false);
			  $e(obj['id']).value = val ? val : obj['default'];
		}
		break;
	  case "select":
		if ($e(obj['id'])) {
		   var val = GetResponseFromServer2("get", "key="+obj['key'], false);
		   $e(obj['id']).selectedIndex = val ? val : obj['default'];
		}
		break;
	}
  }
}

function getUserPrefParams()
{
  if(configWrapper) {
	for(var i=0;i<ObjectsUpdateConfig.length;++i)
	{
	  var obj = ObjectsUpdateConfig[i];
	  try
	  {
		switch(obj['type'])
		{
		  case "textbox":
			{
			  ObjectsSaveConfig[obj['id']+"_sv"] = configWrapper.getUnicharPref(obj['key']);
			}
			break;
		  case "select":
			{
			   ObjectsSaveConfig[obj['id']+"_sv"] = configWrapper.getIntPref(obj['key']);
			}
			break;
		}		
	  }
	  catch(e)
	  {
		ObjectsSaveConfig[obj['id']+"_sv"] = obj['default'];
	  }
	}
	
	try{
	  dir_dest = configWrapper.getUnicharPref("destDir");
          if(!dir_dest)dir_dest = getLocalString("task.dest.default");
	  //dir_temp = configWrapper.getUnicharPref("tempDir");
	  ServerIp = configWrapper.getUnicharPref("severIp");
	  if(!ServerIp)ServerIp = "127.0.0.1";
	  ServerPort = MASTERPORT;
	  isTaskAutoRemove = configWrapper.getIntPref("autoDel");
	  tongetherNumeber = configWrapper.getIntPref("togNum");
	  ifRenameDest = configWrapper.getBoolPref("renameStrategy");
	  
	  var mcurl = configWrapper.getCharPref('mcexlasturl');
	  if(mcurl)MCEXPAGEURL = mcurl;
	  //ServerPort = configWrapper.getCharPref("serverPort");
	  //var inputUrl = configWrapper.getUnicharPref("inputUrl");
	  $e("ipTextBox").value = ServerIp;
	  $e("portTextBox").value = ServerPort;
	  //$e("intput_url").value = inputUrl
	  var langId = configWrapper.getIntPref("langId");
	  $e("setLanguage").selectedIndex = langId;
	  var skinId = configWrapper.getIntPref("skinId");
	  $e("setSkin").selectedIndex = skinId;
      $e("setRemoveDone").selectedIndex = 1 - isTaskAutoRemove;
	  if ($e("setTogetherNumber")) $e("setTogetherNumber").selectedIndex = tongetherNumeber - 1;
	} catch (e) {
	  dumpMsg(e);
	  dir_dest = getLocalString("task.dest.default");
	  dir_temp = "D:\\temp";
	  ServerIp = "127.0.0.1";
	  ServerPort = MASTERPORT;
      isTaskAutoRemove = 1;
	  tongetherNumeber = 1;
	  ifRenameDest = true;
	  $e("ipTextBox").value = ServerIp;
	  $e("portTextBox").value = ServerPort;
	  $e("setLanguage").selectedIndex = 0;
	  $e("setSkin").selectedIndex = 0;
      $e("setRemoveDone").selectedIndex = 1;
	  if ($e("setTogetherNumber")) $e("setTogetherNumber").selectedIndex = 0;
	}
  }
}

function saveUserPrefParams()
{
  if(configWrapper) {
	configWrapper.setUnicharPref("destDir", dir_dest);
	//configWrapper.setUnicharPref("tempDir", dir_temp);
	configWrapper.setUnicharPref("severIp", ServerIp);
	configWrapper.setCharPref("serverPort", ServerPort);
	configWrapper.setIntPref("langId", $e("setLanguage").selectedIndex);
	configWrapper.setIntPref("skinId", $e("setSkin").selectedIndex);
	configWrapper.setIntPref("autoDel", isTaskAutoRemove);
	configWrapper.setIntPref("togNum", tongetherNumeber);
	configWrapper.setBoolPref("renameStrategy", ifRenameDest);
	for(var i=0;i<ObjectsUpdateConfig.length;++i)
	{
	  var obj = ObjectsUpdateConfig[i];	 
	  switch(obj['type']) {
		case "textbox":
		  configWrapper.setCharPref(obj['key'], ObjectsSaveConfig[obj['id']+"_sv"]);
		  break;
	  }		 
	}
	//configWrapper.setUnicharPref("inputUrl", $e("intput_url").value);
	var uri = $e('mcex_page').currentURI;
	//alert(uri.host+ uri.path);
	if(uri.path.indexOf('/index.php?') == 0)
	  configWrapper.setCharPref('mcexlasturl', 'http://' + uri.host + uri.path + '&mcport=18181');
	else
	{
	  configWrapper.setCharPref('mcexlasturl', '');
	}
	//configWrapper.setCharPref('mcexlasturl', '');
  }
}


}