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

var AppCatalogService = Class.create( {
	initialize: function() {
		Mojo.Log.info("---------------- Initialziing app catalog service ------------");
	},
	
	getServerUrl: function() {
		Mojo.Log.info("NovaAccountService.accountServiceIdentifier ======= "+AppCatalogService.accountServiceIdentifier);
		return new Mojo.Service.Request(AppCatalogService.accountServiceIdentifier, {
				method: 'getServerUrl',
				parameters: {},
				onSuccess: (function(response){
					Mojo.Log.info(" OnSuccess.readServerUrl = %o " , $H(response));
					if (response.serverUrl) {
						AppCatalogService.findappsServerURL = response.serverUrl;
					}
					else  {
						Mojo.Log.error(" onFailure.readServerUrl = %o " , $H(response));
					}
					Mojo.Log.info(" this.findappsServerURL = %o ", AppCatalogService.findappsServerURL);
				}).bind(this),
				onFailure: 	(function(response){
					Mojo.Log.error(" onFailure.readServerUrl = %o " , $H(response));
					
				}).bind(this)});	
	},
	
	getServerUrlForScene: function(successCallback, errorCallback, sceneController) {
		return sceneController.serviceRequest(AppCatalogService.accountServiceIdentifier, {
				method: 'getServerUrl',
				parameters: {},
				onSuccess: successCallback,
				onFailure: errorCallback
		})			
	},
	
	getInstalledAppsList: function(params, successCallback, errorCallback)
	{
		Mojo.Log.info("------------------- request params -------------%j", params);
		return new Ajax.Request(AppCatalogService.findappsServerURL + AppCatalogService.getUserInstalledAppsApi, {
			method:"POST",
			contentType:"application/json",
			postBody: Object.toJSON(params),
			onSuccess: successCallback,
			onFailure: errorCallback
		});
	},
	
	installApp: function (currentApp, accountToken, devId, callback) {
		Mojo.Log.info("install called with appLocation = %j", currentApp);
		var params = this.getAppInfoDetails(currentApp, accountToken, devId);
		Mojo.Log.info("install called with appLocation params = %j", params);
		return new Mojo.Service.Request(AppCatalogService.applicationManagerServiceIdentifier, {
			method: 'install',
			parameters: params,
			onSuccess: callback,
			onFailure: callback
		}, true);
	},
	
	getAppInfoDetails: function (currentApp, accountToken, devId) {
		try {
			var params = {
				"id": currentApp.publicApplicationId,
				"title": currentApp.title,
				"vendor": currentApp.creator,
				"vendorUrl": currentApp.vendorURL,
				"iconUrl": currentApp.appIconBig,
				"ipkUrl": currentApp.appLocation,
				"installedSize": currentApp.installedSize,
				"version": currentApp.version,
				"authToken": accountToken, 
				"deviceId": devId
			}
			return params;
		} catch (err) {
			return "";
		}	
	}
});

AppCatalogService.accountServiceIdentifier = 'palm://com.palm.accountservices'
AppCatalogService.getUserInstalledAppsApi = "getUserInstalledApps_ext2";
AppCatalogService.applicationManagerServiceIdentifier = 'palm://com.palm.appInstallService';
