package net.yak.stalk;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URLDecoder;

import net.yak.stalk.Talk.Terp;
import net.yak.stalk.Talk.Terp.Frame;

import com.sun.net.httpserver.*;

public class WebServer {

	static String htmlEscape(String s) {
		return s.replace("&", "&amp;").replace("<", "&lt;")
				.replace(">", "&gt;").replace("\"", "&quot;");
	}
	
	// This is the response {eval=%5B+%2FVec+new+setn%3A+8+%5D+run++at%3A+3+pu%3A+9}

	public static class TerpHandler implements HttpHandler {
		Terp terp;

		public TerpHandler() {
			super();
			this.terp = new Terp();
		}
		@SuppressWarnings("deprecation")
		public void handle(HttpExchange t) throws IOException {
			InputStream is = t.getRequestBody();
			String submissions = readAll(is); // .. read the request body
			String s = submissions.substring(5);
			String evalMe = URLDecoder.decode(s);

			String response = "This is the response {"
				+ htmlEscape(submissions) + "} "
				+ " {" + htmlEscape(evalMe) + "} "
					+ "<form method=post action=/postit>"
					+ "  <input name=eval value=0> "
					+ "  <input type=submit value=Submit /> " + "</form>";

			Expr expr = Parser.parse(terp, evalMe);
			Frame f = terp.newFrame(null, null, null);
			String result = "";
			try {
				result = expr.eval(f).toString();
			} catch (Exception e) {
				result = "ERROR: " + e.toString();
			}

			response += "<pre>\n" + result + "\n</pre>";

			Headers respHeads = t.getResponseHeaders();
			respHeads.set("Content-Type", "text/html");
			t.sendResponseHeaders(200, response.length());
			OutputStream os = t.getResponseBody();
			os.write(response.getBytes());
			os.close();
		}
		public String readAll(InputStream is) throws IOException {
			StringBuffer b = new StringBuffer();
			while (true) {
				int c = is.read();
				if (c < 0)
					break;
				b.append((char) c);
			}
			return b.toString();
		}

	}

	public static void main(String[] args) throws IOException {
		HttpServer server = HttpServer.create(new InetSocketAddress(8000), 5);
		server.createContext("/", new TerpHandler());
		server.setExecutor(null); // creates a default executor
		server.start();
	}

}
