/*
 * Copyright 2009 Palm, Inc. All rights reserved.
 */
/*global Mojo, Class, $L, NetworkMonitor, UrlManager, palmGetResource */
/*jslint rhino:true, undef:true */

function AppAssistant() 
{
}

AppAssistant.Network = new NetworkMonitor();

AppAssistant.prototype.setup = function() 
{
    Mojo.Log.info("Help App#AppAssitant setup");
};


AppAssistant.prototype.handleLaunch = function(launchParams) 
{
    this.jumpToUrl = launchParams.target;

    Mojo.Log.info("Help App#handleLaunch: launchParams %j", launchParams);

	this.checkDebug( );
    this.getDeviceInfo( );
};

AppAssistant.prototype.checkForStage = function() 
{
    if (this.jumpToUrl)
    {
        // Redirect pages with "index.html" to new "index.json" files
        this.jumpToUrl = this.jumpToUrl.replace( /index\.html/, 'index.json' );

        // Redirect pages from base url to correct locale/carrier/device to avoid extra redirecting
        if (this.jumpToUrl.match( /^http:\/\/help\.palm\.com\/\w+\/index.json/ ))
        {
            this.jumpToUrl = this.jumpToUrl.replace( /^http:\/\/help\.palm\.com/, UrlManager.getBaseUrl() );
            Mojo.Log.info("Modified incoming url to: " + this.jumpToUrl);
        }
    }

    var scene = null;
    if (this.jumpToUrl !== undefined && this.jumpToUrl.length > 0) 
    {
        if (this.jumpToUrl == "no-network") 
        {
            scene = 'no-network';
        } 
        else if (this.jumpToUrl.endsWith( ".html" ))
        {
            scene = 'article';
        }
        else if (this.jumpToUrl.endsWith( ".json" ))
        {
            scene = 'json';
        }
        else
        {
            // For example, search will launch: "http://help.palm.com/search/results.cgi?q=<term>"
            scene = 'article';
        }
    } 

    var stageName = "Help";
    var stage = Mojo.Controller.getAppController().getStageController( stageName );
    if (!stage)
    {
        Mojo.Log.info("Creating stage '%s'", stageName);
        Mojo.Controller.getAppController().createStageWithCallback( 
                {name: stageName, lightweight: true}, 
                function(stageController)
                {
                    stageController.pushScene( {name: 'home'} ); 

                    Mojo.Log.info("Created stage, pushed home, now pushing scene: " + scene);
                    if (scene) {
                        stageController.pushScene( {name: scene}, this.jumpToUrl );
					}
                }.bind(this)
            );
    }
    else
    {
        Mojo.Log.info("Activating stage '%s'", stageName);
        stage.activate();

        if (scene)
        {
            Mojo.Log.info("Pushing scene '%s' onto active help app", scene);

            // don't push the same ulr twice!
            if (stage.topScene().assistant.url != this.jumpToUrl)
            {
                Mojo.Log.info("Created stage, pushed home, now pushing scene: " + scene);
                stage.pushScene( {name: scene}, this.jumpToUrl ); 
            }
        }
    }

};

AppAssistant.prototype.getDeviceInfo = function() 
{
    try 
    {
        var self = this;
        this.request = new Mojo.Service.Request('palm://com.palm.systemservice', {
            method: 'getPreferences',
            parameters: { keys: ['locale','x_palm_carrier'] },
            onSuccess:function(response) 
                {
                    if (response.locale) 
                    {
                        UrlManager.setLocale(response.locale.languageCode + '-' + response.locale.countryCode);
                    }

                    if (response.x_palm_carrier) 
                    {
                        UrlManager.setCarrier(response.x_palm_carrier);
                    }
                    else if (Mojo.Environment.version.match('desktop')) 
                    {
                        UrlManager.setCarrier('c019-00'); // Sprint
                    }

                    self.getDeviceId();
                },
            onFailure: function(response) 
                {
                    self.getDeviceId();
                }
            }
        );
    }
    catch (e) 
    {
        Mojo.Log.logException(e);
        this.getDeviceId();

    }
};

AppAssistant.prototype.getDeviceId = function() 
{
    try 
    {
        this.request = new Mojo.Service.Request('palm://com.palm.preferences/systemProperties', 
            {
                method: 'Get',
                parameters: { key: 'com.palm.properties.PRODoID' },
                onSuccess:function(response) 
                {
                    var devId = response['com.palm.properties.PRODoID'];
                    if (devId) 
                    {
                        UrlManager.setDevice(devId);
                    }
					this.checkForStage();
					// this.getProfileInfo();
                }.bind(this),
                onFailure: function() 
                {
					this.checkForStage();
					// this.getProfileInfo();
                }.bind(this)
            }
        );
    }
    catch (e) 
    {
        Mojo.Log.logException(e);
		this.checkForStage();
		// this.getProfileInfo();
    }
};

AppAssistant.prototype.getProfileInfo = function() {
	try {
		this.request = new Mojo.Service.Request('palm://com.palm.accountservices',
			{
				method: 'getAccountInfo',
				parameters: {},
				onSuccess: function(response) {
					Mojo.Log.info("Poked: AppAssistant.getProfileInfo(): email: " + response.email);
                    this.checkForStage();
				}.bind(this),
				onFailure: function() {
					Mojo.Log.info("Poked: AppAssistant.getProfileInfo(): failed to obtain profile email address.");
                    this.checkForStage();
				}.bind(this)
			}
		);
	} catch (e) {
		Mojo.Log.logException(e);
		this.checkForStage();
	}
};

AppAssistant.prototype.checkDebug = function() {
	var debugInfo = palmGetResource('/media/internal/hprvw.txt', true);
	if (debugInfo) {
		debugInfo = Mojo.parseJSON(debugInfo);
		if (debugInfo) {
			UrlManager.baseUrlNoInfo = debugInfo.review_site || UrlManager.baseUrlNoInfo;
			AppAssistant.showCopyInfoMenu = debugInfo.copy_info_menu;
		}
	}
};
