package com.eactive.eai.agent.lifecycle;

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.lifecycle.LifecycleManager;
import com.eactive.eai.common.lifecycle.LifecycleVO;
import com.eactive.eai.common.util.ApplicationContextProvider;
import com.eactive.eai.common.util.Logger;

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

	public RemoveLifecycleCommand(String name) {
		super(name);
	}

	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);
		}

		String keyName = (String) args;

		try {
			LifecycleManager manager = ApplicationContextProvider.getContext().getBean(LifecycleManager.class);
			if (manager != null || keyName != null) {
				manager.removeLifecycle(keyName);
			} else {
				throw new Exception("keyName is null");
			}
		} catch (Exception e) {
			String rspErrorCode = "RECEAIMCM002";
			String msg = makeException(rspErrorCode, e);
			if (logger.isError())
				logger.error(msg, e);
			throw new CommandException(msg);
		}
		return "success";

	}

	// public static void main(String args[]) throws Exception {
//	   test(String args[]);
//}

//private static void test(String args[]) throws Exception {
//        LifecycleVO vo = new LifecycleVO(args[0], -1);
//        Command command = new RemoveLifecycleCommand("RemoveLifecycleCommand");
//        command.setArgs(vo);
//        AgentUtil.broadcast(command);
//    }
}
