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


function AppAssistant(appController) {
    this.appController = appController;
	window.document.addEventListener(Mojo.Event.deactivate, this.onBlurHandler.bind(this));
	window.document.addEventListener(Mojo.Event.activate, this.onFocusHandler.bind(this));	
	
	// register for entering msm notifications
 	this.storageNotificationSession = new Mojo.Service.Request(
		'palm://com.palm.bus/signal',
		{
			method: 'addmatch',
			parameters:
			{
				"category" : "/storaged",
				"method" : "MSMProgress",
				"subscribe" : true
			},
			onSuccess: AppAssistant.prototype.storagedProgress,
			onComplete: AppAssistant.prototype.storagedProgress
		}
	);
}

AppAssistant.lowMemoryNotification = function(level){
	AppAssistant.memoryState = level;
	
	if (this._lowMemoryCallback){
		this._lowMemoryCallback(level);
	}
}

AppAssistant.setLowMemoryCallback = function(callback){
	AppAssistant._lowMemoryCallback = callback;
}


function StageAssistant(stageController) {
	Mojo.Log.info("Youtube: @@@@@@@@@@@@@@@@@@@@@@@@@@ StageAssistant");
	AppAssistant.myStageController = stageController;
	
	// make it work on the desktop
	if (PalmSystem.version.indexOf("desktop") >= 0) {
		AppAssistant.prototype.internetConnectionUpdateCb(
			{isInternetConnectionAvailable: true, wifi : {state: "connected"}});
	}
	else {
		AppAssistant.prototype._startConnectionWatch();
	}
}

AppAssistant.prototype.handleLaunch = function() {
	Mojo.Log.info("Youtube: @@@@@@@@@@@@@@@@@@@@@@@@@@ handleLaunch");
	
	if (AppAssistant.myStageController) {
		Mojo.Log.info("Youtube: handleLaunch youtube is already running");
		AppAssistant.appRelaunch = true;
		AppAssistant.prototype._startConnectionWatch();
		
		// make it work on the desktop
		if (PalmSystem.version.indexOf("desktop") >= 0) {
			AppAssistant.prototype.internetConnectionUpdateCb(
				{isInternetConnectionAvailable: true, wifi : {state: "connected"}});
		}
	}
};

AppAssistant.prototype.startYoutube = function() {
	Mojo.Log.info("Youtube: @@@@@@@@@@@@@@@@@@@ startYoutube");
	var launchParams = {};
	try {
		Mojo.Log.info("Youtube: @@@@@@@@@@@@@@@@@@@ startYoutube launch Params: %j", PalmSystem.launchParams);
		launchParams = PalmSystem.launchParams.evalJSON(true);
	} 
	catch (err) {
		Mojo.Log.info("Youtube: No launch params");
	}
	
	// determine the state app is currently in
	var sceneStack = AppAssistant.myStageController.getScenes();
	
	var appIsRunning = true;
	var homeScenePresent = false;
	var noWifiScenePresent = false;
	
	if (!sceneStack || sceneStack.size() == 0) {
		appIsRunning = false;
	}
	
	if (sceneStack) {
		for (var index = sceneStack.size()-1; index >= 0; index--) {
			var scene = sceneStack[index];
			if (scene.sceneName == "home") {
				homeScenePresent = true;	
			}
			else if (scene.sceneName == "no-wifi") {
				noWifiScenePresent = true;	
			}	
		}
		
		//handle the case when there is no home scene and existing youtube app was launched by other application
		//directly to video scene
		if (sceneStack.size() == 1 && scene.sceneName == "nowplaying") {
		AppAssistant.myStageController.popScene();
		}
	}
	
	Mojo.Log.info("Youtube: @@@@@@@@@@@@@@@@@@@ startYoutube app is running == %s", appIsRunning);
	Mojo.Log.info("Youtube: @@@@@@@@@@@@@@@@@@@ startYoutube homeScenePresent == %s", homeScenePresent);
	Mojo.Log.info("Youtube: @@@@@@@@@@@@@@@@@@@ startYoutube noWifiScenePresent == %s", noWifiScenePresent);
			
	if (launchParams.target && launchParams.target.indexOf("watch?v=") >= 0) {
		if (appIsRunning) {
			AppAssistant.myStageController.popScenesTo("home");
		}
		
		var videoId = launchParams.target.substr(launchParams.target.indexOf("watch?v=") + "watch?v=".length);
		if (videoId.indexOf("&") >= 0) {
			// erase the remainder of URL in case it looks something like this:
			// http://www.youtube.com/watch?v=qJoCfqWdvdQ&feature=channel
			videoId = videoId.substr(0, videoId.indexOf("&"));
		}
		
		AppAssistant.api.lookupVideo(videoId, 
			function(video) {
				if (video) {
					Mojo.Log.info("Youtube: startYoutube lookupVideo video %j", video);
					
					//If launch parameter direct set to true then launch video directly
					if (launchParams.direct) {
						if (appIsRunning) {
							AppAssistant.myStageController.activate();
						}
						AppAssistant.common.playVideo(video);
						
					}
					else 
						AppAssistant.myStageController.pushScene("video", video, !homeScenePresent);
				}
				else {
					Mojo.Log.error("Youtube: startYoutube lookupVideo failed");
					// in case lookup failed do nothing...
					if (appIsRunning) {
						// just focus
						AppAssistant.myStageController.activate();
					}
					if (!homeScenePresent) {
						AppAssistant.myStageController.pushScene("home");
					}
					
					Mojo.Controller.appController.showBanner(
						{messageText: $L("YouTube: Could not find that video")}, null);
				}
			}, 
			function(err) {
				Mojo.Log.error("Youtube: startYoutube lookupVideo failed %s", err);
				// in case lookup failed do nothing...
				if (appIsRunning) {
					// just focus
					AppAssistant.myStageController.activate();
				}
				if (!homeScenePresent) {
					AppAssistant.myStageController.pushScene("home");
				}
				
				Mojo.Controller.appController.showBanner(
					{messageText: $L("YouTube: Could not find that video")}, null);
			});
	}
	else if (launchParams.query) {
		// show the search scene
		if (appIsRunning) {
			AppAssistant.myStageController.popScenesTo("home");
		}
		AppAssistant.myStageController.pushScene("search", launchParams.query, "search", !homeScenePresent);
	}	
	else {
		if (noWifiScenePresent) {
			AppAssistant.myStageController.popScenesTo("home");
		}
		if (appIsRunning) {
			// just focus
			AppAssistant.myStageController.activate();
		}
		if (!homeScenePresent) {
			AppAssistant.myStageController.pushScene("home");
		}
	}
};
	 	 
AppAssistant.prototype.internetConnectionUpdateCb = function(response) {
	Mojo.Log.info("Youtube: @@@@@@@@@@@@@@@@@@@@@@@@@@@@ internetConnectionUpdateCb");
	Mojo.Log.info("Youtube: internetConnectionUpdateCb %j", response);
	if (response) {
		var sceneStack = AppAssistant.myStageController.getScenes();
		
		// if there is no internet connection prompt the user to turn it on
		// show no-wifi scene only if app have just been launched
		if (!response.isInternetConnectionAvailable) {
			if (AppAssistant.appRelaunch) {
				AppAssistant.myStageController.activate();	
			}
			
			if (!sceneStack || sceneStack.size() == 0) {
				Mojo.Log.info("Youtube: internetConnectionUpdate network NOT available show no-wifi scene");
				Mojo.Controller.stageController.pushScene("no-wifi", response.wifi.state);
			}
			else {
				AppAssistant.prototype.showConnectionWidget(response.wifi.state);
			}
		}
		else {
			// if internet is available we are certainly not in MSM
			AppAssistant.MSMmodeActive = false;
			
			if (!sceneStack || sceneStack.size() == 0 
				|| (sceneStack.size() == 1 && AppAssistant.myStageController.topScene().sceneName == "no-wifi") 
				|| AppAssistant.appRelaunch) 
			{
				Mojo.Log.info("Youtube: internetConnectionUpdateCb scene stack is empty calling startYoutube()");
				AppAssistant.api.initializeOnConnected();
				AppAssistant.prototype.startYoutube();
				AppAssistant.appRelaunch = false;
			}
		}
	}		
};

AppAssistant.prototype.cleanup = function() {
	Mojo.Log.info("Youtube: AppAssistant cleanup");
	this._cleanupConnectionWatch();		
	this.storageNotificationSession.cancel();
};

AppAssistant.prototype.onBlurHandler = function() {
	Mojo.Log.info("Youtube: onBlurHandler");
	this._cleanupConnectionWatch();	
};

AppAssistant.prototype.onFocusHandler = function() {
	Mojo.Log.info("Youtube: @@@@@@@@@@@@@@@@@@@@@@@@@@ onFocusHandler");
	this._startConnectionWatch();
};

AppAssistant.prototype._startConnectionWatch = function() {
	Mojo.Log.info("Youtube: _startConnectionWatch");
	// sign up for connection notifications
	if (!AppAssistant.connectionInfoRequest) {
		Mojo.Log.info("Youtube: _startConnectionWatch creating new connectionInfoRequest");
		AppAssistant.connectionInfoRequest = new Mojo.Service.Request("palm://com.palm.connectionmanager", {
			method: 'getstatus',
			parameters: {
				'subscribe': true
			},
			onSuccess: AppAssistant.prototype.internetConnectionUpdateCb
		}, true);
	}
};

AppAssistant.prototype._cleanupConnectionWatch = function() {
	Mojo.Log.info("Youtube: _cleanupConnectionWatch");
	if (AppAssistant.connectionInfoRequest) {
		AppAssistant.connectionInfoRequest.cancel();
		AppAssistant.connectionInfoRequest = null;
	}
	// close connection's widget stage if active
	ConnectionWidget.cancel();
};

AppAssistant.prototype.showConnectionWidget = function(wifiState) {
	// popup connection widget if wifi is disconnected and we are not in MSM
	if (wifiState == "disconnected" && !AppAssistant.MSMmodeActive) {
		Mojo.Log.info("Youtube: showConnectionWidget calling connection widget");
		// popup connection widget
		var params = {type: "data", onSuccess: function() {}};
		ConnectionWidget.connect(params, Mojo.Controller.stageController);
	}
};

AppAssistant.prototype.storagedProgress = function(response) {	
	if (!response) {
		return;
	}
	Mojo.Log.info ("Youtube: AppAssistant storagedProgress: %j", response);
	if (response.stage == 'attempting') {
		Mojo.Log.info ("Youtube: AppAssistant storagedProgress: in MSM");
		AppAssistant.MSMmodeActive = true;
	}
};


/* Globals */
AppAssistant.appMenuModel = {
	items: [
		Mojo.Menu.editItem,  
		{label: $L('Help'), command: 'help'}
	]};
	
AppAssistant.crypto = new Crypto;
AppAssistant.net = new YoutubeNet;
AppAssistant.api = new YoutubeAPI;
AppAssistant.common = new Common;
AppAssistant.history = new HistoryTable;
