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.layout.Layout;
import com.eactive.eai.transformer.layout.LayoutManager;

public class LayoutServlet 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 key = request.getContext();
		
		boolean isReload = false;
		if (key.endsWith("/reload")) {
			isReload = true;
    		key = key.substring(0, key.lastIndexOf('/'));
    	}    	

    	if (key.lastIndexOf('/') == -1) {
    		key = "";
    	} else {
    		key = key.substring(key.indexOf('/')+1);
    	}

    	String result = "";
		try {
			if (isReload) {
				result = reload(key);
			} else {
				result = show(key);
			}
		} catch(Throwable e) {
			result = "<pre>" + ExceptionStackTrace.dump(e) + "</pre>";
		}
    	
		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";	

	public String show(String key) {
		StringBuffer sb = new StringBuffer();
		LayoutManager manager = LayoutManager.getManager();
		String[] messageNames = manager.getAllLayoutName();

    	sb.append(SCRIPT);
    	sb.append("message | key = " + key);
    	sb.append("<br>");
    	
    	int count = 0;
    	for(int i=0; i<messageNames.length; i++) {
			if ("".equals(key.trim()) || messageNames[i].indexOf(key) != -1) {
				count++;
			}
		}
    	
    	int resultCount = 0;
		for(int i=0; i<messageNames.length; i++) {
			if ("".equals(key.trim()) || messageNames[i].indexOf(key) != -1) {
				if (count > 1) {
		    		sb.append("<div style=\"height: 17px; margin: 0px 0px 0px 0px;overflow: hidden;padding:0px 0px 0px 0px;cursor:hand;\" ondblclick=\"toggle(this)\">");
				}
				Layout l = manager.getLayoutByName(messageNames[i]);
				if(l != null) {
					sb.append("<pre style=\"padding:0px 0px 0px 0px;margin: 0px 0px 0px 0px\">");
			    	sb.append("(<a href='/message/" + messageNames[i] + "/reload'>reload</a>)&nbsp;");
					sb.append(l.getRootItem().toString());
					sb.append("</pre>");
				} 
				else {
					sb.append("<pre style=\"padding:0px 0px 0px 0px;margin: 0px 0px 0px 0px\">");
			    	sb.append("(<a href='/message/" + messageNames[i] + "/reload'>reload</a>)&nbsp;");
					sb.append("Layout not found!");
					sb.append("</pre>");
				}

				if (count > 1) {
		    	   	sb.append("</div>");
		    	   	sb.append("<div style=\"height: 1px; overflow: hidden;border:0px;background-color:black;\"></div>");
				}
				
				/**
				 * 10개 까지만 뿌려준다.
				 */
				if (resultCount++ >= 100)
					break;
			}
		}
		return sb.toString();
	}
	
	public String reload(String key) throws Exception {
		if (LayoutManager.getManager().getLayoutByName(key) == null)
			return "layout '" + key + "' does not exist";
		
		LayoutManager.getManager().reload(key);
		return "reload message '" + key + "' successfully";
	}	
}