dojo.provide("ecnext.JsonService");
dojo.declare("ecnext.JsonService", null, {
	uri: '',
	constructor: function(kwArgs) {
		if (!"uri" in kwArgs || !kwArgs.uri)
			throw(new Error("usage: new ecnext.JsonService({uri})"));

		this.uri = kwArgs.uri;
	},

	sendMessage: function(kwArgs) {
		var msg = {};
		if ("msg" in kwArgs) {
			msg = kwArgs.msg;
		}

		return this._post(msg);
	},

	_post: function(msg) {
		var dResult = new dojo.Deferred();
		var dXhrResult = dojo.xhrPost({
			url: this.uri,
			content: msg,
			handleAs: "json",
			load: function(response) {
				if (response.exceptionClassName) {
					var error = new Error(response.exceptionClassName);
					error.response = response;
					dResult.errback(error);
				}
				else {
					dResult.callback(response.result);
				}
			},
			error: function(response, ioArgs) {
				var error = response;
				if (ioArgs.xhr.responseText) {
					var msg;
					try {
						msg = dojo.fromJson(ioArgs.xhr.responseText);
						if (typeof msg != 'object') {
							throw(new Error("internal html error"));
						}
					}
					catch (ex) {
						msg = {
							exceptionClassName: 'InternalHtmlException',
							exceptionDetails: '',
							result: null
						};
					}
					error = new Error(msg.exceptionClassName || 'UnknownException');
					error.response = msg;
					error.prevError = response;
				}
				else {
					error.response = null;
				}
				dResult.errback(error);
			}
		});

		return dResult;
	},

	zLastFunction: function() {}
});
