/************************************************************************ 
  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(g_executeInBatch) == "undefined")
{
	Include("Wrappers/Common.js")
	Include("Controllers/Controller.js");
}

if (typeof(Scenario) == "undefined")
	Scenario = {};


Scenario.FlashUpdater = 
{
	name: 			"Flash.Updater",
	displayName:    "Adobe Flash",
	version: 		"1.3",
	description: 	"Checks if Flash update is enabled and allows to disable and enable update facilities",
	link:			"http://www.updatefreezer.org/index.php?id=2",
	icon:			"Resources/Flash.Updater.png",
	actions:		["query", "backup", "restore", "enable", "disable"],

	programs:		[{path: "%WINDIR%\\SysWOW64\\Macromed\\Flash"},
					 {path: "%WINDIR%\\System32\\Macromed\\Flash"}],
	inherits: 		[ScenarioController],
	
//#region Implementation
	flashPlayerDataFileName: "Adobe.FlashPlayer.json",

	_getFlashCfgFilePath: function()
	{
		/*
		The mms.cfg file is a UTF-8 text file.
		The format of the mms.cfg file is a series of name=value pairs separated by carriage returns. 
		If a parameter is not set in the file, Flash Player assumes the default value. 
		When set, values in this file override the user-configured settings stored in a per-user local shared object.
		Windows 95, 98, or ME--C:\Windows\System\Macromed\Flash
		Windows NT, 2000-- C:\WINNT\System32\Macromed\Flash
		Windows XP, Vista --C:\WINDOWS\System32\Macromed\Flash
		Windows 64-bit -- C:\Windows\SysWOW64
		*/
		var wd = Util.Shell.GetEnvironmentVariable("WINDIR");
		if(wd.length == 0)
		{
			if(l1) Warning(S("Adobe.Updater.errUnknownWindirPath"));
			return "";
		}
		var path = "";
		if(Util.Shell.IsWin64())
		{
			path = wd + "\\SysWOW64";
		}
		else
		{
			path = wd + "\\System32\\Macromed\\Flash";
		}
		return path + "\\mms.cfg";
	},
	
	_EnumerateFlashPlayer: function()
	{
		var p = [];
		var cfgPath = this._getFlashCfgFilePath();
		if(cfgPath.length == 0)
			return;
		var fp = {"name" : "FlashPlayer", "enabled": true};
		/*
		We suppose that flash player installed.
		AutoUpdateDisable
		0 allows auto-update based on user settings.
		1 disables auto-update.
		*/
		if(Util.IO.CheckFileExists(cfgPath))
		{
			var text = Util.IO.ReadFile(cfgPath);
			var re = /^\s*AutoUpdateDisable\s*=\s*([0-1])\s*$/im;
			var res = text.match(re);
			if (res != null)
			{
				if (res.length > 1 && res[1] == "1")
				{
					fp.enabled = false;
				}
			}
		}
		p.push(fp);
		return p;
	},
	
	QueryFlashPlayer: function()
	{
		var result = {
			products:[],
			hasProducts: function()
			{
				return this.products.length > 0;
			},
			hasEnabled: function()
			{
				for(var i = 0; i < this.products.length; i++)
				{
					if (this.products[i].enabled)
						return true;
				}
				return false;
			}
		};
		
		result.products = this._EnumerateFlashPlayer();
		var dataFileName =  Util.IO.CombinePath(this.dataFolderPath, this.flashPlayerDataFileName);
		Util.IO.WriteJsonToFile(dataFileName, result);
		
		if (result.hasProducts())
		{
			if (result.hasEnabled())
			{
				this.updaterEnabled = true;
				queryResult.push({msg: S("Adobe.Updater.FpEnabled")});
			}
			else
				queryResult.push({msg: S("Adobe.Updater.FpDisabled")});
		}
		else
		{
			queryResult.push({msg: S("Adobe.Updater.FpNotFound")});
		}
		return result;
	},
	
	ChangeFlashPlayer: function(enable)
	{
		var dataFileName =  Util.IO.CombinePath(this.dataFolderPath, this.flashPlayerDataFileName);
		var p = Util.IO.ReadJsonFromFile(dataFileName);
		if (p && p.products)
		{
			for(var i = 0; i < p.products.length; i++)
			{
				var product = p.products[i];
				var et = enable;
				if (enable === undefined)
					et = product.enabled;
				if(product.name == "FlashPlayer")
				{
					var cfgPath = this._getFlashCfgFilePath();
					if(cfgPath.length == 0)
						continue;
						
					var val = et ? "0" : "1";
					var text = "AutoUpdateDisable=" + val + "\n";

					if(Util.IO.CheckFileExists(cfgPath))
					{
						text = Util.IO.ReadFile(cfgPath);
						var re = /^\s*AutoUpdateDisable\s*=\s*([0-1])\s*$/im;
						var res = text.match(re);

						if (res != null && res.length > 1)
							text = text.replace(re, "AutoUpdateDisable=" + val);
						else
							text = "AutoUpdateDisable=" +  val + "\n" + text;
					}
					Util.IO.WriteFile(cfgPath, text);
				}
			}
		}
	},
//#endregion	

	
//#region Actions
	Query: function()
	{
		if (!this.CheckProgramInstalled())
		{
			return false;
		}	
	
		this.QueryFlashPlayer();
		this.LogUpdaterStatus();
	},
	
	Disable: function()
	{
		this.ChangeFlashPlayer(false);
	},
	
	Enable: function()
	{
		this.ChangeFlashPlayer(true);
	},
	
	Backup: function()
	{
		this.QueryFlashPlayer();
	},
	
	Restore: function()
	{
		this.ChangeFlashPlayer();
	}
//#endregion	
	

};


Util.Scenario.InitializeScenario(Scenario.FlashUpdater);

if (typeof(g_executeInBatch) == "undefined")
{
	Util.Locale.Load();
	Execute(Scenario.FlashUpdater);
}

Scenario.FlashUpdater.OutputDependencies();
