package com.eactive.eai.transformer.servlet;

import com.eactive.eai.adapter.socket2.common.ExceptionStackTrace;
import com.eactive.eai.adapter.socket2.config.SocketAdapterManager;
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 com.eactive.eai.transformer.engine.TransformEngine;
import com.eactive.eai.transformer.util.MemoryLogger;

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

	protected void doService(HttpRequest request, HttpResponse response) throws Exception {
		String command = request.getContext();
    	if (command.lastIndexOf('/') == -1) {
    		command = "";
    	} else {
    		command = command.substring(command.indexOf('/')+1);
    	}

    	String result = "";
    	if (command == null || "".equals(command) || "tx".equals(command)) {
			try {
				result = transaction();
			} catch(Throwable e) {
				result = "<pre>" + ExceptionStackTrace.dump(e) + "</pre>";
			}  		
    	} else if ("error".equals(command) || "err".equals(command)) {
			try {
				result = error();
			} catch(Throwable e) {
				result = "<pre>" + ExceptionStackTrace.dump(e) + "</pre>";
			}  		
    	} else if ("dump".equals(command)) {
			try {
				result = dump();
			} catch(Throwable e) {
				result = "<pre>" + ExceptionStackTrace.dump(e) + "</pre>";
			}  		
    	} else {
    		response.setResponseCode(404);
    		return;
    	}
    	
		response.setContentType("text/html");
		response.setResponseCode(HttpResponse.HTTP_STATUS_SUCCESS);
		response.appendBody(result);
	}

	final static String SCRIPT =
		"	<script>                                        \n" +
        "		function toggle(obj){                       \n" +
        "			if (obj.style.height == \"17px\"){      \n" +
        "				obj.style.height=\"\";              \n" +
        "				obj.style.overflow=\"visible\";     \n" +
        "			}else{                                  \n" +
        "				obj.style.height=\"17px\";          \n" +
        "				obj.style.overflow=\"hidden\";      \n" +
        "			}                                       \n" +
        "		}                                           \n" +
        "	</script>                                       \n";
	
	private String transaction() throws Exception {
		StringBuffer sb = new StringBuffer();
    	String[] transactions = MemoryLogger.getTransactions();
    	sb.append(SCRIPT);

    	sb.append("<h3>Transformer - transactions</h3>");
    	for (int i=transactions.length-1; i>=0; i--) {
    		sb.append("<div style=\"height: 17px; margin: 0px 0px 0px 0px;overflow: hidden;padding:0px 0px 0px 0px;cursor:hand;\" ondblclick=\"toggle(this)\">");
        	sb.append("<pre style=\"padding:0px 0px 0px 0px;margin: 0px 0px 0px 0px\">");
    	   	sb.append(unescape(transactions[i]));
    	   	sb.append("</pre>");
    	   	sb.append("</div>");
    	   	sb.append("<div style=\"height: 1px; overflow: hidden;border:0px;background-color:black;\"></div>");
    	}
		return sb.toString();
	}
	
	private String error() throws Exception {
		StringBuffer sb = new StringBuffer();
    	String[] errors = MemoryLogger.getErrors();
    	sb.append(SCRIPT);

    	sb.append("<h3>Transformer - errors (" + MemoryLogger.getErrorCount() + ")</h3>");
    	for (int i=errors.length-1; i>=0; i--) {
    		sb.append("<div style=\"height: 17px; margin: 0px 0px 0px 0px;overflow: hidden;padding:0px 0px 0px 0px;cursor:hand;\" ondblclick=\"toggle(this)\">");
        	sb.append("<pre style=\"padding:0px 0px 0px 0px;margin: 0px 0px 0px 0px\">");
    		sb.append(unescape(errors[i]));
    	   	sb.append("</pre>");
    	   	sb.append("</div>");
    	   	sb.append("<div style=\"height: 1px; overflow: hidden;border:0px;background-color:black;\"></div>");
    	   	
	    }
		return sb.toString();
	}
	
	
	private String dump() throws Exception {
		StringBuffer sb = new StringBuffer();
    	sb.append("<h3>Transformer - dump</h3>");
    	sb.append("<pre>");
		sb.append(TransformEngine.getInstance().toString());
    	sb.append("</pre>\n");
		return sb.toString();
	}
	

    
    private String unescape(String string) {
    	string = string.replace("<b>", "(b)").replace("</b>", "(/b)");
    	string = string.replaceAll("<a( href=\\'[a-zA-Z0-9_/]+\\')>", "(a$1)").replace("</a>", "(/a)");
    	string = string.replaceAll("<font color='([a-zA-Z]+)'>", "(font color='$1')").replace("</font>", "(/font)");
    	string = string.replace(">", "&gt;").replace("<", "&lt;");
    	string = string.replace("(b)", "<b>").replace("(/b)", "</b>");
    	string = string.replaceAll("\\(a( href=\\'[a-zA-Z0-9_/]+\\')\\)", "<a$1>").replace("(/a)", "</a>");
    	string = string.replaceAll("\\(font color='([a-zA-Z]+)'\\)", "<font color='$1'>").replace("(/font)", "</font>");
    	return string;
    }
}
