/************************************************************************ 
  Copyright 2011-2012, IceJS Team. All rights reserved.
  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are
  met:
  
      * Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
      * Redistributions in binary form must reproduce the above
        copyright notice, this list of conditions and the following
        disclaimer in the documentation and/or other materials provided
        with the distribution.
      * Neither the name of Update Freezer Team nor the names of its
        contributors may be used to endorse or promote products derived
        from this software without specific prior written permission.
  
  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ***********************************************************************/ 

if (typeof(ScenarioController) == "undefined")
{
	Include("Controllers/Scenario.Controller.js");
}	

var MozillaController = 
{
	actions:		["query", "backup", "restore", "disable", "setauto", "setmanual", "setnotset"],

	inherits: [ScenarioController],
	
	ReadCfgFile: function(p, shift)
	{
		//var cfg = p + ".freezer";
		//if(Util.IO.ShiftFileBytes(p, cfg, shift))
		{
			var t = Util.IO.ReadFile(p);
			if(t.indexOf("//") == 0)
			{
				return t; // file decoded
			}
		}
		return Util.IO.ReadFile(p);
	},
	
	QueryMozillaProduct: function()
	{
		var result = 
		{
			path: "",
			enabled: true,
			autoUpdate: true,
			state: 0, // 0 - no config file, 1 - config file present, 2 - app.update.enabled lock present
			exist: false
		};	

		// check only installed products
		result.path = Util.Shell.ExpandEnvironmentString(this.product.path);
		var pc = Util.Process.GetProcessesCount(this.product.procName);
		if(pc > 0)
		{
			if(l1) Log1(SF("Mozilla.Controller.processRunning", [this.product.procName, true]));
		}
			
		if(Util.IO.CheckFileExists(result.path))
		{
			// we do not check real settings here since they vary for each user.
			//search update settings in custom config instead
			result.exist = true;
			var ls = result.path + this.localSettingsPath;
			if(Util.IO.CheckFileExists(ls))
			{
				var ft = Util.IO.ReadFile(ls);
				var lsText = 'pref("general.config.filename", "' + this.config + '");\n';
				if(ft.indexOf(lsText) >= 0)
				{
					// only when config file set
					var cfg = result.path + this.config;
					if(Util.IO.CheckFileExists(cfg))
					{
						result.state = 1;
						var t = this.ReadCfgFile(cfg, 13);
						var re = /^lockPref\([\s'\"]*app.update.enabled[\s'\"]*,[\s'\"]*(true|false)[\s'\"]*\);/im;
						var res = t.match(re);
						if (res != null && res.length > 1)
						{
							result.state = 2;
							if(res[1] == "false")
							{
								result.enabled = false;
							}
						}
						re = /^lockPref\([\s'\"]*app.update.auto[\s'\"]*,[\s'\"]*(true|false)[\s'\"]*\);/im;
						res = t.match(re);
						if (res != null && res.length > 1)
						{
							if(res[1] == "false")
							{
								result.autoUpdate = false;
							}
						}
					}
				}
			}

			if(!result.enabled)
			{
				queryResult.push({msg: SF("Mozilla.Controller.ProductDisabled", [this.product.name])});
			}
			else
			{
				this.updaterEnabled = true;
				queryResult.push({msg: SF("Mozilla.Controller.ProductEnabled", [this.product.name])});
			}
		}
		else
		{
			queryResult.push({msg: SF("Mozilla.Controller.PoductNotFound", [this.product.name])});
		}

		var dfn =  Util.IO.CombinePath(this.dataFolderPath, this.dataFileName);
		Util.IO.WriteJsonToFile(dfn, result);
	},

	ChangeMozillaProduct: function(action)
	{
		var dfn =  Util.IO.CombinePath(this.dataFolderPath, this.dataFileName);
		var p = Util.IO.ReadJsonFromFile(dfn);
		if (p && p.exist)
		{
			var pc = Util.Process.GetProcessesCount(this.product.procName);
			if(pc > 0)
			{
				if(l1) Log1(SF("Mozilla.Controller.processRunning", [this.product.procName, true]));
			}

			var enabled = p.enabled;
			var auto = p.autoUpdate;
			switch(action)
			{
				case this.DISABLED: //1
					enabled = false;
					auto = false;
					break;
				case this.NOTIFYONLY://2
					enabled = true;
					auto = false;
					break;
				case this.AUTOMATIC://3
					enabled = true;
					auto = true;
					break;
				case this.NOTSET:
					this.RemoveFreezerOverride();
					return;
				case undefined:
					if(p.state < 2)
					{
						// no lock were before change, so we must remove lock
						this.RemoveFreezerOverride();
						return;
					}
					break;
			}
			this.SetProductState(p, enabled, auto);
			
			//tell the application to load the lock file. 
			//Create a new file in the defaults/pref subfolder of the installation directory.
			var lsText = 'pref("general.config.obscure_value", 0);\n';
			lsText += 'pref("general.config.filename", "' + this.config + '");\n';
			var ls = p.path + this.localSettingsPath;
			Util.IO.CreateDirectory(p.path + this.localSettingsDir);
			if(Util.IO.CheckFileExists(ls))
			{
				Util.IO.DeleteFile(ls);
			}
			Util.IO.WriteFile(ls, lsText);
		}
	},
	
	RemoveFreezerOverride: function()
	{
		var p = Util.Shell.ExpandEnvironmentString(this.product.path);
		if(Util.IO.CheckFileExists(p + this.config))
		{
			Util.IO.DeleteFile(p + this.config);
		}
		if(Util.IO.CheckFileExists(p + this.localSettingsPath))
		{
			Util.IO.DeleteFile(p + this.localSettingsPath);
		}
	},
	
	AreFreezerOverrideSet: function()
	{
		var p = Util.Shell.ExpandEnvironmentString(this.product.path);
		if(!Util.IO.CheckFileExists(p + this.config))
		{
			return false;
		}
		if(!Util.IO.CheckFileExists(p + this.localSettingsPath))
		{
			return false;
		}
		return true;
	},
	
	SetProductState: function(product, enabled, auto)
	{
		var cfg = product.path + this.config;
		var en = enabled ? "true" : "false";
		var av = auto ? "true" : "false";
		var ens = 'lockPref("app.update.enabled",' + en + ');';
		var avs = 'lockPref("app.update.auto",' + av + ');';
		// file must start with //
		var t = "//\n" + ens + "\n" + avs; 
		if(Util.IO.CheckFileExists(cfg))
		{
			t = Util.IO.ReadFile(cfg);
			var re = /^lockPref\([\s'\"]*app.update.enabled[\s'\"]*,[\s'\"]*(true|false)[\s'\"]*\);/im;
			var res = t.match(re);
			if (res != null && res.length > 1)
			{
				t = t.replace(re, ens);
			}
			else
			{
				t = t + '\n' + ens;
			}
			re = /^lockPref\([\s'\"]*app.update.auto[\s'\"]*,[\s'\"]*(true|false)[\s'\"]*\);/im;
			res = t.match(re);
			if (res != null && res.length > 1)
			{
				t = t.replace(re, avs);
			}
			else
			{
				t = t + '\n' + avs;
			}
		}
		Util.IO.WriteFile(cfg, t);
	},
	
	NOTSET:			 0,
	DISABLED: 		 1,
	NOTIFYONLY: 	 2,
	AUTOMATIC: 		 3,

	Query: function()
	{
		if (!this.CheckProgramInstalled())
		{
			return false;
		}	
	
		this.QueryMozillaProduct();
		
		if (this.updaterEnabled)
		{
			queryResult.push({msg: "<b>" + SF("Mozilla.Controller.UpdaterEnabled", [this.product.name]) + "</b>"});
		}
		else
		{
			queryResult.push({msg: "<b>" + SF("Mozilla.Controller.UpdaterDisabled", [this.product.name]) + "</b>"});
		}
	},
	
	Disable: function()
	{
		this.ChangeMozillaProduct(this.DISABLED);
	},
	
	SetAuto: function()
	{
		this.ChangeMozillaProduct(this.AUTOMATIC);
	},
	
	SetManual: function()
	{
		this.ChangeMozillaProduct(this.NOTIFYONLY);
	},
	
	SetNotSet: function()
	{
		this.ChangeMozillaProduct(this.NOTSET);
	},
	
	Backup: function()
	{
		this.QueryMozillaProduct();
	},
	
	Restore: function()
	{
		this.ChangeMozillaProduct();
	},

	GetScenarioInfo: function()
	{
		Scenario.currentScenario = this;
		
		if (this.IsProgramInstalled)
		{
			if (false == this.IsProgramInstalled())
			{
					return {name: this.name, 
							displayName: this.displayName,
							icon: this.icon,
							status: S("UI.NotInstalled"),
							link: this.link};
			}
		}

		// do backup if first time
		var backupFolder = Util.Scenario.GetDataFolderPath(this.name, "backup");		
		var files = _GetFilesInFolder(backupFolder);
		if (files.length == 0)
		{
			action = "backup";
			Execute(this);
		}
	
		// do query
		this.updaterEnabled = false;
		action = "query";
		var status = Execute(this);
		var dfn =  Util.IO.CombinePath(this.dataFolderPath, this.dataFileName);
		var result = Util.IO.ReadJsonFromFile(dfn);
		var updaterEnabled = this.updaterEnabled;
		var state = this.NOTSET;
		if(this.AreFreezerOverrideSet())
		{
			var enabled = false;
			var auto = false;
			if (result.enabled)
			{
				enabled = true;
			}
			if (result.autoUpdate)
			{
				auto = true;
			}
			if(enabled)
			{
				if(auto)
				{
					state = this.AUTOMATIC;
				}
				else
				{
					state = this.NOTIFYONLY;
				}
			}
			else
			{
				state = this.DISABLED;
			}
		}
		var actionInfo = 
		{
			name: this.name,
			displayName: this.displayName,
			icon: this.icon,
			status: status,
			link: this.link,
		    actions: [
				{
					action: "SetNotSet",
					buttonName: "NotSet",
					active: state == this.NOTSET
				},
				{
					action: "Disable",
					buttonName: "Disabled", 
					active: state == this.DISABLED
				},
				{
					action: "SetManual", 
					buttonName: "NotifyOnly", 
					active: state == this.NOTIFYONLY
				},
				{
					action: "SetAuto",
					buttonName: "Automatic",
					active: state == this.AUTOMATIC
				}
				
			]
		};
	
		return actionInfo;
	}
}