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

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.common.util.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;

public class ControlServlet extends HttpServlet {
	static final 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 = "<?xml version=\"1.0\" encoding=\"euc-kr\" ?>";
    	try {
	    	if (command == null || "".equals(command) || "list".equals(command)) {
	    		result += list(request.getParameter("adapter"));
	    	} else if (command.startsWith("start")) {
	    		result += start(request.getParameter("adapter"));
	    	} else if (command.startsWith("stop")) {
	    		result += stop(request.getParameter("adapter"));
	    	} else if (command.startsWith("free")) {
	    		result += free(request.getParameter("adapter"));
	    	} else {
	    		response.setResponseCode(404);
	    		return;
	    	}
		} 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){
			filter = null;
		}
		if (filter == null){
			return cmd(" ps -ef | grep tcp ");
		}else{
			return cmd(" ps -ef | grep tcp | grep "+filter);
		}
	}
	private String free(String filter) {
//		boolean verbose = false;		
//		StringBuffer sb = new StringBuffer();
		try{
			filter = URLDecoder.decode(filter,"UTF-8");
		}catch(Exception e){
			filter = null;
		}
		if (filter == null){
			return "";
		}else{
			return cmd(filter);
		}
	}	
	private String start(String filter) {
//		boolean verbose = false;		
//		StringBuffer sb = new StringBuffer();
		try{
			filter = URLDecoder.decode(filter,"UTF-8");
		}catch(Exception e){
			filter = null;
		}
		if (filter == null){
			return "";
		}else{
			return cmd(" devstart "+filter);
		}
	}	
	private String stop(String filter) {
//		boolean verbose = false;		
//		StringBuffer sb = new StringBuffer();
		try{
			filter = URLDecoder.decode(filter,"UTF-8");
		}catch(Exception e){
			filter = null;
		}
		if (filter == null){
			return "";
		}else{
			return cmd(" devstop "+filter);
		}
	}	
	
	private String cmd(String command){
		
		StringBuffer sb = new StringBuffer();
	    try {
		    String[] cmd = new String[] {"sh", "-c", command};
		    Runtime runtime = Runtime.getRuntime();
		    Process process = runtime.exec(cmd);
		    
//	        Process process = new ProcessBuilder(cmd).start();
	        
		    StreamGobbler gb1 = new StreamGobbler(process.getInputStream());
		    StreamGobbler gb2 = new StreamGobbler(process.getErrorStream());
		    gb1.start();
		    gb2.start();
	        
		    while (true) {
		        if (!gb1.isAlive() && !gb2.isAlive()) {  //두개의 스레드가 정지할면 프로세스 종료때까지 기다린다.
		        	process.waitFor();
		        	sb.append(gb1.getData());
		            break;
		        }
		    }
		    
//	        InputStream is = process.getInputStream();
//	        InputStreamReader isr = new InputStreamReader(is);
//	        BufferedReader br = new BufferedReader(isr);        
//	        int result = process.waitFor();
//	        sb.append("<result>");
//	    	String line;
//	        while ((line = br.readLine()) != null) {
//	        	sb.append("<row>");
//	            sb.append( line + "\n");
//	            sb.append("</row>");
//	        }        
//	        sb.append("</result>");
    	} catch(Exception e) {
    		// ignore
    		sb.append("cmd failed");
	    }
    	return sb.toString();
	}
//	private String prop() {
//		return "";
//	}	
	
	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;
	}
	class StreamGobbler extends Thread
	{
	    InputStream is;
	    StringBuffer sb ;
	    public StreamGobbler(InputStream is) {
	        this.is = is;
	        sb = new StringBuffer();
	    }

	    public void run()
	    {
	        try {
	            InputStreamReader isr = new InputStreamReader(is);
	            BufferedReader br = new BufferedReader(isr);
		        sb.append("<result>");
		    	String line;
		        while ((line = br.readLine()) != null) {
		        	sb.append("<row>");
		            sb.append( line + "\n");
		            sb.append("</row>");
		        }        
		        sb.append("</result>");
	        } catch (IOException ioe) {
	          logger.info("run error - "+ ioe.toString());
	        }
	    }
	    public String getData(){
	    	return sb.toString();
	    }
	}	
}
