package online.struts.chain.processor;

import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

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 ServletActionContext sac = ServletActionContext.class.cast(context);

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

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

		final String prefix = context.getModuleConfig().getPrefix();
		if (!path.startsWith(prefix)) {
			final String 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 int slash = path.lastIndexOf('/');
			if (period > slash) {
				path = path.substring(slash, period);
			} else {
				path = path.substring(0, period);
			}
		}

		return path;
	}
}
