package com.eactive.eai.agent.authserver;

import com.eactive.eai.agent.command.Command;
import com.eactive.eai.agent.command.CommandException;
import com.eactive.eai.authserver.service.OAuth2Manager;
import com.eactive.eai.common.util.Logger;
import java.util.Arrays;

@SuppressWarnings("serial")
public class ReloadApiScopeCommand extends Command {
	public static final String COMMAND_TYPE_API = "API";
	public static final String COMMAND_TYPE_SCOPE = "SCOPE";
	public static final String COMMAND_TYPE_API_SCOPE = "API-SCOPE";

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

	/**
	 * args[0]: type(API, SCOPE, API-SCOPE)<br>
	 * args[1]: apiId<br>
	 * args[2]: scopeId
	 */
	@Override
	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 {
			OAuth2Manager manager = OAuth2Manager.getInstance();

			String[] keyName = (String[]) args;

			if (keyName != null) {
				manager.reloadApiScopeRelation(keyName);
				if (logger.isWarn()) {
					logger.warn(this.name + "] " + Arrays.toString(keyName) + " 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";
	}
}
