package com.eactive.eai.agent.adapter;

import com.eactive.eai.adapter.AdapterGroupVO;
import com.eactive.eai.adapter.AdapterManager;
import com.eactive.eai.adapter.http.dynamic.HttpDynamicInAdapterManager;
import com.eactive.eai.adapter.http.healthcheck.HttpTargetMonitorManager;
import com.eactive.eai.agent.command.Command;
import com.eactive.eai.agent.command.CommandException;
import com.eactive.eai.common.util.Logger;

public class RemoveAdapterGroupCommand extends Command {
	private static final long serialVersionUID = 1L;

	public RemoveAdapterGroupCommand() {
		super("RemoveAdapterGroupCommand");
	}

    /** 
    * 1. 기능 :  AdapterManager에 AdapterGroupVO를 제거
    * 2. 처리 개요 : AdapterGroupVO의 EAISvrInstNm이 DEFAULT_SERVER(ALL) 이거나  LocalServer인 경우
    *           AdapterManager에 등록된 해당 AdapterGroupVO를 제거
    * 3. 주의사항 
    *
    * @exception    CommandException	Argument Type이 다르거나 Command 수행중 Excpetion이 발생할 경우
    **/

	public Object execute() throws CommandException {
		Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
		if (logger.isInfo())
			logger.info(this.name + " is executed");

		if (!(args instanceof String)) {
			String rspErrorCode = "RECEAIMCM001";
			String msg = makeException(rspErrorCode, null);
			if (logger.isError())
				logger.error(msg);
			throw new CommandException(msg);
		}

		AdapterManager manager = AdapterManager.getInstance();
		String adapterGroupName = null;
		try {
			adapterGroupName = (String) args;
			AdapterGroupVO gvo = manager.getAdapterGroupVO(adapterGroupName);
			if (gvo != null) {
				gvo.stop();
				manager.removeAdapterGroupVO(adapterGroupName);
			}
		} catch (Exception e) {
			String rspErrorCode = "RECEAIMCM002";
			String msg = makeException(rspErrorCode, e);
			if (logger.isError())
				logger.error(msg, e);
			throw new CommandException(msg);
		}

		// HTTP, REST inbound Adapter PathMap remove
		try {
			HttpDynamicInAdapterManager dynamicManager = HttpDynamicInAdapterManager.getInstance();
			dynamicManager.removeAdptUriMapByAdapterGroupName(adapterGroupName);
		} catch (Exception e) {
			String rspErrorCode = "RECEAIMCM002";
			String msg = makeException(rspErrorCode, e);
			if (logger.isError())
				logger.error(msg, e);
		}
		
		try {
			HttpTargetMonitorManager monitorManager = HttpTargetMonitorManager.getInstance();
			monitorManager.removeHttpHeacthCheckerWithGroupName(adapterGroupName);
		} catch (Exception e) {
			String rspErrorCode = "RECEAIMCM002";
			String msg = makeException(rspErrorCode, e);
			if (logger.isError())
				logger.error(msg, e);
		}
		
		return "success";
	}
}
