package org.positrium.waket.handler;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;

import org.positrium.waket.AbstractDataServerHandler;
import org.positrium.waket.DataServerHandler;

import com.sun.net.httpserver.HttpExchange;

import dareka.common.CloseUtil;
import dareka.common.Config;
import dareka.processor.HttpHeader;
import dareka.processor.HttpUtil;

public class ProxyPacHandler extends AbstractDataServerHandler implements
		DataServerHandler {

	@Override
	public String getUri() {
		return this.uri;
	}

	@Override
	public void handle(HttpExchange he) throws IOException {
		File file = new File(Config.getString("dhtProxyPac", "proxy.pac"));
		he.sendResponseHeaders(HttpURLConnection.HTTP_OK, file.length());
		he.getResponseHeaders().set(HttpHeader.CONTENT_TYPE, "text/plain");
		if (file.exists()) {
			OutputStream out = he.getResponseBody();
			InputStream in = new FileInputStream(file);
			try {
				HttpUtil.sendBody(out, in, file.length());
			} finally {
				CloseUtil.close(out);
				CloseUtil.close(in);
			}
		} else {
			he.sendResponseHeaders(HttpURLConnection.HTTP_NOT_FOUND, 0);
			he.getRequestBody().close();
		}
	}

}
