package com.eactive.eai.adapter.socket2.protocol.http.servlet;

import com.eactive.eai.adapter.socket2.config.SocketLoggerManager;
import com.eactive.eai.adapter.socket2.protocol.http.HttpServlet;
import com.eactive.eai.adapter.socket2.protocol.http.codec.HttpRequest;
import com.eactive.eai.adapter.socket2.protocol.http.codec.HttpResponse;
import com.eactive.eai.common.util.Logger;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;

public class GroovyServlet extends HttpServlet {
    static Logger logger = SocketLoggerManager.getInstance().getLogger("FileLogger{NET}_HTTP");

	protected void doService(HttpRequest request, HttpResponse response) throws Exception {
		String method = request.getHeader("Method")[0];    	
		if ("GET".equals(method)) {
			doGet(request, response);
		} else {
			doPost(request, response);
		}
	}

	protected void doGet(HttpRequest request, HttpResponse response) throws Exception {
		StringBuilder sb = new StringBuilder();
		
		sb.append("<form action='groovy' method='post'>");
		sb.append("<textarea rows='30' cols='120'>");		
		sb.append("</textarea>");
		sb.append("<input type='submit' value='submit'/>");
		sb.append("</form>");
		
		response.setContentType("text/html");
		response.setResponseCode(HttpResponse.HTTP_STATUS_SUCCESS);
		response.appendBody(sb.toString());
	}

	protected void doPost(HttpRequest request, HttpResponse response) throws Exception {
//		System.out.println(request.getParameter(""));
		
		StringBuilder sb = new StringBuilder();
		
		Binding binding = new Binding();
		binding.setVariable("request", request);		
		binding.setVariable("response", request);		
		GroovyShell shell = new GroovyShell(binding);
		
	    shell.evaluate(request.getParameter(""));
	    //return (byte[]) binding.getVariable("response");

		sb.append(request);		
	    
		response.setContentType("text/html");
		response.setResponseCode(HttpResponse.HTTP_STATUS_SUCCESS);
		response.appendBody(sb.toString());
	}
}
