/*******************************************************************************
 * Copyright (c) 2000, 2008 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.swt.net;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;

import intrinsic.Function;
import intrinsic.XMLList;
import intrinsic.mx.rpc.AsyncToken;
import intrinsic.mx.rpc.Responder;
import intrinsic.mx.rpc.events.FaultEvent;
import intrinsic.mx.rpc.events.ResultEvent;
import intrinsic.mx.rpc.http.mxml.HTTPService;

public class HttpRequest {
	HTTPService httpService;
	Listener listener;
	
public HttpRequest () {
	httpService = new HTTPService(null);
}

public void setURL (String url) {
	httpService.url = url;
}

public void setUseProxy (boolean useProxy) {
	httpService.useProxy = useProxy;
}

public void setFormat (String format) {
	httpService.resultFormat = format;
}

public void addListener (Listener listener) {
	this.listener = listener;
}

public void invoke () {
	AsyncToken token = httpService.send(null);
	Responder responder = new Responder(resultHandlerFunction(), faultHandlerFunction());
	token.addResponder(responder);
}
	
void resultHandler(Object data) {
	ResultEvent resultEvent = (ResultEvent)data;
	Event event = new Event();
	if ("e4x".equals(httpService.resultFormat)) {
		XMLList list = (XMLList)resultEvent.result;
		event.data = list.toXMLString();
	} else {
		event.data = resultEvent.result;
	}
	listener.handleEvent(event);
}
	
native Function resultHandlerFunction ()/*{
	return resultHandler__Ljava_lang_Object_2;
}*/;

void faultHandler(Object info) {
	FaultEvent faultEvent = (FaultEvent)info;
	Event event = new Event();
	event.data = "empty";
	if (faultEvent != null) {
		if (faultEvent.fault != null) {
			event.data = faultEvent.fault.faultString;
		} else {
			event.data = "faultEvent.fault == null";
		}
	} else {
		event.data = "faultEvent == null";
	}
	event.detail = SWT.ERROR_UNSPECIFIED;//
	listener.handleEvent(event);
}

native Function faultHandlerFunction ()/*{
	return faultHandler__Ljava_lang_Object_2;
}*/;
	
	
}
