/*******************************************************************************
 * Copyright (c) 2005, 2007 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 java.io.*;
import java.net.*;

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


public class HttpRequest {
	Listener listener;
	String url;
	
public HttpRequest () {
}

public void setURL (String url) {
	this.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 () {
	new Thread() {
		public void run() {
			InputStream in = null;
			try {
				HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
				con.setRequestMethod("GET");
				con.setDoOutput(false);
				con.setDoInput(true);
				con.connect();
				in = con.getInputStream();
				BufferedReader reader = new BufferedReader(new InputStreamReader(in));
				final StringBuffer buffer = new StringBuffer();
				String line = null;
				while ((line = reader.readLine()) != null) {
					buffer.append(line);
					buffer.append('\r');
				}
				Display.getDefault().asyncExec(new Runnable() {
					public void run() {
						resultHandler(buffer.toString());
					}
				});
			} catch (Exception e) {
				faultHandler(e);
			} finally {
				try {
					if (in != null) in.close();
		        } catch (Exception ex) {
		        }		
			}
		}
	}.start();
}
	
void resultHandler(Object data) {
	Event event = new Event();
	event.data = data;
	listener.handleEvent(event);
}

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;
	event.data = info.toString();
	listener.handleEvent(event);
}
	
}
