package com.eactive.eai.agent.eaimessage;

import com.eactive.eai.agent.command.Command;
import com.eactive.eai.agent.command.CommandException;
import com.eactive.eai.common.message.EAIMessageManager;
import com.eactive.eai.common.util.Logger;

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

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

	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)) {
			throwCommandException("RECEAIMCM001", null);
		}

		try {
			EAIMessageManager manager = EAIMessageManager.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 {
					if (keyName.contains(",")) {
						reloadKeys(manager, keyName);
					} else {
						manager.reload(keyName.trim());
						if (logger.isWarn()) {
							logger.warn(this.name + "] " + keyName + " Reload.");
						}
					}
				}
			}
		} catch (Exception e) {
			throwCommandException("RECEAIMCM002", e);
		}
		return "success";
	}

	private void reloadKeys(EAIMessageManager manager, String keyName) throws Exception {
		Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
		if (logger.isWarn()) {
			logger.warn(this.name + "] Array [" + keyName + "] Reload.");
		}

		String[] keys = keyName.split(",");
		for (String key : keys) {
			if (key != null) {
				manager.reload(key.trim());
			}
		}
	}

	private void throwCommandException(String errorCode, Exception exception) throws CommandException {
		Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
		String msg = makeException(errorCode, exception);
		if (logger.isError()) {
			logger.error(msg, exception);
		}
		throw new CommandException(msg);
	}
}
