package online.struts.chain.processor;

import java.util.Objects;

import org.apache.logging.log4j.LogManager;
import org.apache.struts.chain.Constants;
import org.apache.struts.chain.commands.AbstractSelectAction;
import org.apache.struts.chain.contexts.ActionContext;
import org.apache.struts.chain.contexts.ServletActionContext;

import core.exception.PhysicalException;

/**
 * パス取得
 *
 * @author Tadashi Nakayama
 * @version 1.0.0
 */
public final class SelectActionProcessor extends AbstractSelectAction {

	/**
	 * @see org.apache.struts.chain.commands.AbstractSelectAction
	 * #getPath(org.apache.struts.chain.contexts.ActionContext)
	 */
	@Override
	protected String getPath(final ActionContext<String, Object> context) {
		// キャスト
		if (!ServletActionContext.class.isInstance(context)) {
			LogManager.getLogger().error(context);
			throw new IllegalStateException(String.valueOf(context));
		}
		final var sac = ServletActionContext.class.cast(context);

		// サーブレット名取得
		final var request = sac.getRequest();
		var path = Objects.toString(request.getAttribute(Constants.INCLUDE_SERVLET_PATH),
						request.getServletPath());

		final var period = path.lastIndexOf('.');
		if (period < 0) {
			// パスインフォ取得
			final var ipath = Objects.toString(
					request.getAttribute(Constants.INCLUDE_PATH_INFO),
					request.getPathInfo());
			if (!Objects.toString(ipath, "").isEmpty()) {
				return ipath;
			}
		}

		final var prefix = context.getModuleConfig().getPrefix();
		if (!path.startsWith(prefix)) {
			final var msg = sac.getActionServlet().getInternal().getMessage("processPath");
			LogManager.getLogger().warn(msg + " " + path);
			throw new PhysicalException("No action config found.", null);
		}

		path = path.substring(prefix.length());
		if (period >= 0) {
			final var slash = path.lastIndexOf('/');
			if (period > slash) {
				path = path.substring(slash, period);
			} else {
				path = path.substring(0, period);
			}
		}

		return path;
	}
}
