// +----------------------+
// | Public RPC client    |
// | Author: Craig Manley |
// +----------------------+
// $Id: RpcClient.js,v 1.2 2009/04/02 14:40:27 cmanley Exp $

// Make sure the required jsolait scripts are loaded.
// /js/jsolait/init.js
// /js/jsolait/lib/urllib.js
// /js/jsolait/lib/jsonrpc.js


/***
 * RpcClient class.
 */
var RpcClient = new (function() {

	// Initialize jsonrpc module and set jsonrpc global.
	var jsonrpc = null;
	try {
		jsonrpc = importModule('jsonrpc');
	}
	catch(e) {
		try { reportException(e); } catch(e) {}
		throw "Importing of jsonrpc module failed.";
	}

	/*** Protected properties ***/
	this._service = (function() {
		var loc = window.document.location;
		var url = loc.protocol + '//' + loc.host	+ '/jsonrpc-server.php';
		var methods = [
			'cartAddItem',
			'cartAddItemsFromOrder'
		];
		return new jsonrpc.ServiceProxy(url, methods);
	})();

	/*** Protected methods ***/
	this._handleRpcException = function(e) {
		//alert(e.constructor.toString());
		var arr = e.constructor.toString().match(/^\[class (\S+)\]$/);
		var classname = arr && arr.length == 2 ? arr[1] : undefined;
		if (classname == 'JSONRPCError') { // Fault
			// e.message.faultCode >= 800 // user exception
			alert("Foutmelding:\n\n" + e.message.faultString);
		}
		else { // this shouldn't happen
			var em;
			if (e.toTraceString) {
				em = e.toTraceString();
			}
			else {
				em = e.message;
			}
			alert(em);
		}
	}

	/*** Public methods ***/
	// Returns a hash with keys 'count' and 'value' on success, else false.
	this.cartAddItemsFromOrder = function(order_id) {
		order_id = parseInt(order_id,10);
		var result = null;
		try {
			result = this._service.cartAddItemsFromOrder(order_id);
		}
		catch(e) {
			this._handleRpcException(e);
		}
		return result;
	}

	// Returns a hash with keys 'count' and 'value' on success, else false.
	this.cartAddItem = function(code, amount) {
		if (amount) {
			amount = parseInt(amount,10);
		}
		else {
			amount = 1;
		}
		var result = null;
		try {
			result = this._service.cartAddItem(code, amount);
		}
		catch(e) {
			this._handleRpcException(e);
		}
		return result;
	};

})();


