/*
 * Copyright (c)  2006-2007 Maskat Project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
maskat.lang.Class.declare("maskat.event.RemoteEventContext")
	.extend("maskat.comm.HttpContext", {

	initialize: function(handler, event){
		this.base(handler.method, handler.url, handler);
		this.handler = handler;
		this.event = event;

		if (!this.requestHeaders["maskat_layoutID"]) {
			this.requestHeaders["maskat_layoutID"] = event.layoutId;
		}
		if (!this.requestHeaders["maskat_componentID"]) {
			this.requestHeaders["maskat_componentID"] = event.widgetId;
		}
		if (!this.requestHeaders["maskat_eventID"]) {
			this.requestHeaders["maskat_eventID"] = event.type;
		}
	},
	
	onWait: function(){
		if (this.handler.onBeforeRequest) {
			var param = {
				sendXML: this.requestMessage,
				xhr: this.xhr,
				stopProcess: false
			};
			try {
				this.handler.onBeforeRequest(param);

				if (param.stopProcess) {
					throw new maskat.lang.InterruptedError("INTERRUPTION_ERROR");
				}
				
			} catch (e) {
				if (e instanceof maskat.lang.InterruptedError) {
					var msg = e.getMessages ? e.getMessages().join("\n") : e.message;
					this.handler.logger.info(msg);
				}
				throw e;
			}
		}
			
		if (!this.async) {
			this.dialog = maskat.ui.Dialog.openProgress(
				"",
				maskat.util.Message.format("SYNC_EVENT_IN_PROGRESS"),
				Infinity);
		}
	},
	
	onComplete: function(){
		if (!this.async) {
			this.dialog.done();
		}

		try {
			if (this.handler.onAfterResponse) {
				var param = {
					recvDOM: this.responseXML,
					xhr: this.xhr,
					stopProcess: false
				};
				this.handler.onAfterResponse(param);
				
				if (param.stopProcess) {
					throw new maskat.lang.InterruptedError("INTERRUPTION_ERROR");
				}
			}
			this.handler.handleResponse(this.event, this);
			
		} catch (e) {
			if (e instanceof maskat.lang.InterruptedError) {
				var msg = e.getMessages ? e.getMessages().join("\n") : e.message;
				this.handler.logger.info(msg);
			}
			throw e;
		}
	},
	
	onTimeout: function(){
		this.handler.handleRequestTimeout(this.event);
	},

	onError: function(){
		this.handler.handleError(this.event, this.error);
	}
	
});
