/* Copyright 2009 Palm, Inc.  All rights reserved. */

var AppAssistant = Class.create({
	
	_name: 'findapps',
	
	initialize: function()
	{
		Mojo.Log.info("AppAssistant::initialize");
	    Weave.Services.ConnectionManager.monitor();
	},
	
	setup: function()
	{
		Mojo.Log.info("AppAssistant::setup");
		
		var self = this;		
		Weave.System.Activator.addInterface('main',
		{
			_defaultStage: "default",
			
			init: function(target)
			{
				var me = this;
				Weave.System.Activator.open(this._defaultStage, "DefaultStageAssistant", function(stage)
				{
					me.start(stage, me._defaultStage);
				});
			},
			
			start: function(stage, stageName)
			{
				Mojo.Log.info("AppAssistant(main) start");
				if (!TermsOfUse.isAccepted())
				{
					stage.controller.pushScene('terms', function(accepted)
					{
						if (accepted) 
						{
							stage._gotoMain();
						}
						else 
						{
							Weave.System.Activator.close(stageName);
						}
					});
				}
				else
				{
					stage._gotoMain();
				}
				//stage.controller.activate();
				
				// is this needed?
				// Delay starting up to try to let the card come up a bit faster
				/*(function()
				{
					stage._gotoMain();
					stage.controller.activate();
				}).delay(1);
				*/
			},
		});
		
		Weave.System.Activator.addInterface('myapps',
		{
			_defaultStage: "default",
			
			init: function(target)
			{
				var me = this;
				Weave.System.Activator.open(this._defaultStage, "DefaultStageAssistant", function(stage)
				{
					me.start(stage, me._defaultStage);
				});
			},
			
			start: function(stage, stageName)
			{
				Mojo.Log.info("AppAssistant(myapps) start");
				
				var top = stage.controller.topScene();
				if (!top || top.sceneName != "myapps") 
				{
					stage.controller.pushScene('myapps');	
				}
				//stage.controller.activate();
			},	
		});
		
		Weave.System.Activator.addInterface('target',
		{
			_defaultStage: "default",
			_webDistributedStage: "webDistributed",
			
			// perform any initialization determine which stage to open
			init: function(target)
			{
				Mojo.Log.info("AppAssistant(target).init target %s", target);
				var ids = self._findAppAndPackageId(target);
				
				// call server to find out the type of this application
				var appDetails = new AppDetails(ids.applicationId, ids.packageId);
				appDetails.attach(this);
				appDetails.getDetailsFromServer();
			},
			
			updateDetails: function(app)
			{
				var stageName = this._defaultStage;
				var stageAssistantName = "DefaultStageAssistant";
				
				var programType = app.getProgramType();
				Mojo.Log.info("AppAssistant(target).updateDetails programType %s", programType);
				
				// figure out which stage to push
				if (programType && (programType == "W" || programType == "B"))
				{
					stageName = this._webDistributedStage + (new Date()).getTime();
					stageAssistantName = "WebDistributedStageAssistant"
				}
				
				var me = this;				
				Weave.System.Activator.open(stageName, stageAssistantName, function(stage)
				{
					me.target(app, stage, stageName);
				})
			},
			
			target: function(app, stage, stageName)
			{
				Mojo.Log.info("AppAssistant(target).target id:%j", app._packageid);
				app.detach(this);
				
				if (!TermsOfUse.isAccepted())
				{
					stage.controller.pushScene('terms', function(accepted)
					{
						if (accepted) 
						{
							stage.controller.swapScene('details', null, null, app);
						}
						else 
						{
							Weave.System.Activator.close(stageName);
						}
					});
				}
				else
				{
					stage.controller.pushScene('details', null, null, app);
				}
				//stage.controller.activate();
			}
		});
	},
	
	cleanup: function()
	{
		Mojo.Log.info("AppAssistant.cleanup");
		if (Catalog && Catalog.AppDownloadMngr)
			Catalog.AppDownloadMngr.cleanup();
			
		Weave.Services.ConnectionManager.cleanup();
	},
	
	handleLaunch: function(params)
    {
		Mojo.Log.info("AppAssistant::handleLaunch params *%j*", params);
		if (!params || params == "")
		{
			params = {main: ""};
		}
		
		Weave.System.Activator.run(params);
    },
	
	_findAppAndPackageId: function(target)
	{
		Mojo.Log.info("AppAssistant::_findAppAndPackageId target", target);
		var matches = /[?&]packageid=([^&]*)(?:&applicationid=(\d*)){0,1}/.exec(target);
		return matches ? { packageId: matches[1], applicationId: matches[2] } : {};
	},
});

var DefaultStageAssistant = Class.create(
{	
	setup: function()
	{
		// Default AppMenu
		var self = this;
		var menu = new Weave.Utilities.AppMenu()
			.addEdit()
			.addItem($L('Preferences & Accounts'), 
				function()
				{
					self.controller.pushScene("prefs");
				},
				function()
				{
					return myProfile.enableAcc;
				})
			.addHelp('http://help.palm.com/app_catalog/index.html');
		Weave.Utilities.AppMenu.setDefault(menu);
		
		Weave.Services.ApplicationServer.getAppCatUserFlags(function(status, response, token)
		{
			//myProfile.country = token.country;
			myProfile.carrier = token.carrier.toLowerCase();
			myProfile.email = token.email;
			if (status ) 
			{
				Mojo.Log.info("GetAppCatUserFlags: status:%j, response:%j, token:%j", status, response, token);
				if(response.enablePaymentSetup)
					myProfile.enableAcc = response.enablePaymentSetup;
				else
					menu._items.splice(1, 1);
			}
			else 
			{
				//In case error at server, check for mcc to activate account--only for US
				Mojo.Log.info("Falling back to mcc..");
				Weave.Services.DeviceProfile.getCarrierIdentification(function(status, response)
				{
					if (status && ((response.mcc >= 310 && response.mcc <= 316) || PalmSystem.version.match("desktop"))) {
						myProfile.enableAcc = true;
					}
					else {
						// No nice way to do this - remove the prefs menu item
						menu._items.splice(1, 1);
					}
				});
			}
		});
	},
	
	_gotoMain: function()
	{
		var mainSceneExists = false;
		var sceneStack = this.controller.getScenes();
		if (sceneStack) 
		{
			for (var index = sceneStack.size()-1; index >= 0; index--) 
			{
				var scene = sceneStack[index];
				if (scene.sceneName == "main") 
				{
					mainSceneExists = true;
					break;
				}
			}
		}
			
		// If we're on the main screen, stay there, otherwise pop all the scenes to main
		var top = this.controller.topScene();
		if (top && top.sceneName != "main") 
		{
			this.controller.popScenesTo("main");
		}
		
		if (!mainSceneExists)
		{
			this.controller.pushScene("main");
		}
	}
});

var WebDistributedStageAssistant = Class.create(
{	
	setup: function()
	{
		// Default AppMenu
		var self = this;
		var menu = new Weave.Utilities.AppMenu()
			.addEdit()
			.addItem($L('Preferences & Accounts'), 
				function()
				{
					self.controller.pushScene("prefs");
				},
				function()
				{
					return myProfile.enableAcc;
				})
			.addHelp('http://help.palm.com/app_catalog/index.html');
		Weave.Utilities.AppMenu.setDefault(menu);
		Weave.Services.ApplicationServer.getAppCatUserFlags(function(status, response, token)
		{
			//myProfile.country = token.country;
			myProfile.carrier = token.carrier.toLowerCase();
			myProfile.email = token.email;
			if (status ) {
				if(response.enablePaymentSetup)
					myProfile.enableAcc = response.enablePaymentSetup;
				else
					menu._items.splice(1, 1);
			}
			else 
			{
				Weave.Services.DeviceProfile.getCarrierIdentification(function(status, response)
				{
					if (status && ((response.mcc >= 310 && response.mcc <= 316) || PalmSystem.version.match("desktop"))) {
						myProfile.enableAcc = true;
					}
					else {
						// No nice way to do this - remove the prefs menu item
						menu._items.splice(1, 1);
					}
				});
			}
		});
	},
	
	/**********************************************
    * Global data
    ***********************************************/
	
	embargoedCounrtyList: undefined,
});
