MSGI.namespace('MSGI.service');

MSGI.service.send = (function() {
	// generate unique ID to be provided with a JSON-RPC request
	var getID = (function() {
		var id = 0;
		return function() {
			return ++id;
		};
	})();
	
	function escapeUnicode(string) {
		return string.replace(/\\u000a/g, '\n').replace(/\\u000d/g, '\r').replace(/\\u0009/g, '\t');
	}

	function prepareRequest(id, method, params) {
		// re-escape characters that were converted to Unicode by JSON.stringify()
		return escapeUnicode(
			// convert hash to a JSON string
			JSON.stringify({ 
				'id': id,
				'method': method, 
				'params': params ? [params] : [] // JSON-RPC server expects params hash to be wrapped in an array
			})
		);
	}

	/**
	 * Low-level utility for sending a JSON-RPC request to the web service API
	 * @param {string} method the name of the API method
	 * @param {object} params (optional) any parameters to be provided to the web service
	 * @param {function} callback the function to be executed when the response is received
	 */
	return function(method, params, callback) {
		if (arguments.length == 2) {
			callback = params;
			params = null;
		}

		var id = getID().toString();
		var request = prepareRequest(id, method, params);
		
		$.post('/service/service.jsp', request, function(json) {
			try {
				var response = jsonParse(json);
			} catch (e) {
				var response = { 'id': id, 'result': null, 'error': 'Error parsing JSON response.' };
			}
			callback(response);
		});
	};
})();
