package com.eactive.eai.agent.messagekey;

import com.eactive.eai.agent.command.Command;
import com.eactive.eai.agent.command.CommandException;
import com.eactive.eai.common.messagekey.MessageKeyManager;
import com.eactive.eai.common.util.Logger;

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

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

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

		try {
			MessageKeyManager manager = MessageKeyManager.getInstance();
			String keyName = (String) args;

			if (keyName != null) {
				if ("ALL".equals(keyName)) {
					manager.reload();
					if (logger.isWarn())
						logger.warn(this.name + "] all rule Reload.");
				} else {
					String[] keys = keyName.split(",");
					manager.reload(keys[0], keys[1]);
					if (logger.isWarn())
						logger.warn(this.name + "] " + keyName + " Reload.");

				}
			} else {
				manager.reload();
				if (logger.isWarn())
					logger.warn(this.name + "] all rule Reload.");
			}
		} 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();
//}

//    private static void test() throws Exception {
//            Command command = new ReloadMessageKeyCommand();
//            command.setArgs("ALL");
//            AgentUtil.broadcast(command);
//    }
}
