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

DownloadRequest = Class.create({

	initialize: function(url) {

		Mojo.require(url, "Request requires a url");
		this.url = url;
	},
	
	download: function(params) {
		
		var callback = params.onDownload || function() {};
		var onDownload = function(success, response) {
			
			if (success) {
				// Map responses to a little more sane status codes.
				if (response.completionStatusCode < 0) {
					callback(success, 'error', response);
					this.close();
				} else if (response.returnValue && response.returnValue === true) {
					this._ticket = response.ticket;
					callback(success, 'start', response);
				} else if (response.returnValue && response.returnValue === false) {
					callback(success, 'error', response);
					this.close();
				} else if (response.aborted) {
					callback(success, 'abort', response);
					this.close();
				} else if (response.interrupted) {
					callback(success, 'interrupted', response);
					this.close();
				} else if (response.completed) {
					callback(success, 'complete', response);
					this.close();
				} else if (response.amountReceived) {
					callback(success, 'progress', response);
				} else {
					callback(success, 'error', response);
					this.close();
				}				
			} else {
				callback(success, 'failure', response);
				this.close();
			}
		};
		
		this._downloadRequest = new Mojo.Service.Request('palm://com.palm.downloadmanager/download', {
			parameters: {
				id: 'com.palm.app.browser',
				'target': this.url, 
				'subscribe': true 
				},
			onSuccess: onDownload.bind(this, true),
			onFailure: onDownload.bind(this, false)
		});
		
	},

	close: function() {
		
		if (this._downloadRequest) {
			this._downloadRequest.cancel();
		}
	},

	cancel: function(params) {
		
		var callback = params.onCancel || function() {};
		
		if (this._ticket) {
		
			var onCancel = function(success, response) {
				callback(success, response);
			};
			
			this._cancelRequest = new Mojo.Service.Request('palm://com.palm.downloadmanager/cancelDownload', {
				parameters: {
					'ticket': this._ticket
				},
				onSuccess: onCancel.bind(this, true),
				onFailure: onCancel.bind(this, false)
			});
		}
	},
	
	open: function(params) {
	
		var callback = params.onOpen || function() {};
		var callParams = { 'mime': params.mimetype, 'target': 'file://' + params.file};

		var onOpen = function(success, response) {
			callback(success, response);	
		};

		this._openRequest = new Mojo.Service.Request('palm://com.palm.applicationManager', {
			method: 'open',
			parameters: callParams,
			onSuccess: onOpen.bind(this, true),
			onFailure: onOpen.bind(this, false)
		});
	}
});
