package com.eactive.eai.adapter.websocket.servlet;

import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.java_websocket.WebSocket;

import com.eactive.eai.adapter.AdapterManager;
import com.eactive.eai.adapter.AdapterVO;
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.adapter.websocket.WebSocketAdapterManager;
import com.eactive.eai.adapter.websocket.WebSocketHandler;
import com.eactive.eai.adapter.websocket.WebSocketSessionManager;
import com.eactive.eai.common.util.Logger;


public class WebSocketAdaptersServlet 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 filter = request.getContext();
    	filter = filter.substring(filter.indexOf('/')+1);
    	if ("websocket".equals(filter)) {
    		filter = null;
    	}
    	
    	String result = "";
    	try {
	    	result = list(filter);
		} catch(Throwable e) {
			result = "<pre>" + ExceptionStackTrace.dump(e) + "</pre>";
		}
		
		if (!"".equals(request.getParameter("refresh"))) {
			response.appendBody("<meta http-equiv='refresh' content=" + request.getParameter("refresh") + "; url=" + request.getContext() + ">\n\n");
		}
		
    	response.setContentType("text/html");
    	response.setResponseCode(HttpResponse.HTTP_STATUS_SUCCESS);
		response.appendBody(result);
	}

	private String list(String filter) {
		boolean verbose = false;		
		StringBuffer sb = new StringBuffer();
		try{
			filter = URLDecoder.decode(filter,"UTF-8");
		}catch(Exception e){
			
		}
		
		ConcurrentHashMap<String, ConcurrentHashMap<String, WebSocketHandler>> adapterGroups = (ConcurrentHashMap)WebSocketAdapterManager.getInstance().getAdapterGroups();
		
		String prevAdapterGroupName = "";
	    for (Enumeration<String> e = adapterGroups.keys(); e.hasMoreElements();) {
	    	String adapterGroupName = e.nextElement();    	
	    	ConcurrentHashMap<String, WebSocketHandler> adapters = adapterGroups.get(adapterGroupName);
	    	
	    	
		    for (Enumeration<WebSocketHandler> ee = adapters.elements() ; ee.hasMoreElements() ;) {
		    	WebSocketHandler adapter = ee.nextElement();
		    	
		    	if (filter != null 
		    		&& adapterGroupName.toLowerCase().indexOf(filter.toLowerCase()) == -1
		    		&& String.valueOf(adapter.getPort()).toLowerCase().indexOf(filter.toLowerCase()) == -1
		    		&& adapter.getAdapterVO().getDescription().indexOf(filter.toLowerCase()) == -1
		    		)
		    		continue;		    	
	    	
		    	if (!adapterGroupName.equals(prevAdapterGroupName)) {
			    	sb.append("ⓖ " + adapterGroupName);
			    	sb.append("\n");
		    	}

		    	//sb.append("    ⓐ <a href='/adapter/show?adapter=" + adapterGroupName + "." + adapter.getAdapterVO().getName() + "'>");
		    	sb.append("    ⓐ <a href=''>");
		    	sb.append(adapter.getAdapterVO().getName());
		    	sb.append("</a>");

		    	sb.append("\n       ");
		    	sb.append("<font color='gray'>");
	    		sb.append("<b>");
		    	sb.append(" ServerPort : "+adapter.getPort());
	    		sb.append("</b>");
		    	sb.append("</font>");
		    	
	    		sb.append("\n<font color='gray'>");
	    		WebSocketSessionManager manager = WebSocketSessionManager.getInstance();
	    		ConcurrentHashMap<String,WebSocket> pool =  manager.getSessionList(adapterGroupName);
	    		
			    for (Iterator iii = pool.keySet().iterator() ; iii.hasNext(); ) {
			    	
			    	String key = (String) iii.next();
			    	WebSocket session = pool.get(key);
			    	
			    	sb.append("        ");
			    	sb.append("⊙ id="+key+" Session :"+session.getLocalSocketAddress() +" <- "+session.getRemoteSocketAddress());
			    	sb.append("\n");
			    }
			    sb.append("</font>");
		    
			    sb.append("\n");

			    prevAdapterGroupName = adapterGroupName;
		    }
	    }		

        return "<pre>" + sb.toString() + "</pre>";
	}
	
	protected boolean getAdapterStatus(String adapterGroupName, String adapterName) {
        AdapterManager manager = AdapterManager.getInstance();
        AdapterVO vo = manager.getAdapterVO(adapterGroupName, adapterName);
        if (vo != null) {
        	return vo.isStatus();
        }
        return false;
	}
}
