package com.eactive.eai.agent.web;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URLConnection;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.eactive.eai.agent.AgentUtil;
import com.eactive.eai.agent.command.Command;
import com.eactive.eai.agent.command.CommandException;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.server.Keys;
import com.eactive.eai.common.util.Logger;

/**
 * 1. 기능 : AdapterGroupVO ADD 
 * 2. 처리 개요 : AdapterGroupVO를 manager에 add 
 * 3. 주의사항
 *
 * @author
 * @version v 1.0.0
 * @see 관련 기능을 참조
 * @since
 * 
 */
public class WebAgent extends HttpServlet {
	static final String PARAMETER_MESSAGE = "_message_";
	public static final String FIELD_INST_NAME = "INST_NAME";
	public static final String FIELD_INTERNAL_URL = "INTERNAL_URL";
	public static final String FIELD_IS_CLOUD_PROXY = "IS_CLOUD_PROXY";
	public static final String INST_NAME = System.getProperty(Keys.SERVER_KEY);
	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

	protected void execute(Command command) throws CommandException {
		try {
			command.execute();

		} catch (CommandException ce) {
			// System.out.println("WebAgent Servlet] execute() occur CommandException :" + ce.toString());
			// ce.printStackTrace();
			throw ce;
		} catch (Exception e) {
			String errorMsg = ExceptionUtil.make(e, "RECEAIMCM010");
			if (logger.isError())
				logger.error(errorMsg, e);
			throw new CommandException(errorMsg);
		}
	}

	/**
	 * 1. 기능 : 요청으로 전달된 Command 실행 
	 * 2. 처리 개요 : 요청으로 전달된 Command 실행하고 실행된 결과를 ObjectOutStream을 통해 전송 
	 * 3. 주의사항
	 *
	 * @param request  HttpServletRequest
	 * @param response HttpServletResponse
	 * @return
	 * @exception
	 **/
	@Override
	public void service(HttpServletRequest request, HttpServletResponse response) {

		ObjectInputStream is = null;
		ObjectOutputStream os = null;
		try {
			is = new ObjectInputStream(request.getInputStream());
			os = new ObjectOutputStream(response.getOutputStream());

			Command command = (Command) is.readObject();

			// 20220718 컨테이너 외부 EMS에서 커맨드 호출 시 다른컨테이너의 커맨드인 경우 전달 처리
			if ("true".equals(request.getHeader(FIELD_IS_CLOUD_PROXY))
					&& !INST_NAME.equals(request.getHeader(FIELD_INST_NAME))) {
				logger.info("Execute Command Proxy: " + command.getName() + ", TARGET_INST_NAME:"
						+ request.getHeader(FIELD_INST_NAME) + ", TARGET_URL:" + request.getHeader(FIELD_INTERNAL_URL));
				String iUrl = request.getHeader(FIELD_INTERNAL_URL);
				URLConnection urlCon = AgentUtil.getURLConnection(iUrl);
				urlCon.setConnectTimeout(3000);
				urlCon.setReadTimeout(2000);

				AgentUtil.sendCommand(urlCon, command);

				String result = "success";
				os.writeObject(result);
			} else {
				logger.info("Execute Command Local: " + command.getName());
				execute(command);

				String result = "success";
				os.writeObject(result);
			}

		} catch (Exception e) {
			logger.error("WebAgent sync error " + e.getMessage(), e);
			response.setStatus(500);

			try {
				os.writeObject(e.getMessage());
			} catch (Exception ex) {
				logger.warn("writeObject error", e);
			}

		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (Exception e) {
				}
			}
			if (os != null) {
				try {
					os.close();
				} catch (Exception e) {
				}
			}
		}

	}
}
