package online.struts.filter;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts.Globals;
import org.apache.struts.config.ModuleConfig;

import online.filter.FilterUtil;
import online.filter.RouteRequestFilter;
import online.struts.mapping.RequestMapping;

/**
 * ルート制御フィルタ
 *
 * @author Tadashi Nakayama
 * @version 1.0.0
 */
public final class RoutingFilter extends RouteRequestFilter {

	/**
	 * @see online.filter.RouteRequestFilter
	 * #findTargetPath(javax.servlet.ServletContext, javax.servlet.http.HttpServletRequest)
	 */
	@Override
	protected int findTargetPath(final ServletContext context, final HttpServletRequest request) {
		final var mc = ModuleConfig.class.cast(context.getAttribute(Globals.MODULE_KEY));
		if (mc != null) {
			final var path = FilterUtil.toPlainURI(request.getRequestURI());
			for (int s = path.lastIndexOf('/'), e = path.length(); 0 <= s;
					e = s, s = path.lastIndexOf('/', path.offsetByCodePoints(e, -1))) {
				final var val = path.substring(s, e);
				if (val.endsWith(".do") || val.endsWith(".jsp") || val.endsWith(".jspx")
						|| val.endsWith(".css") || val.endsWith(".js")) {
					break;
				}
				final var ac = mc.findActionConfig(val);
				if (ac != null) {
					if (!FilterUtil.isGetMethod(request.getMethod())) {
						break;
					} else if (RequestMapping.class.isInstance(ac)) {
						final var rm = RequestMapping.class.cast(ac);
						if (rm.getKeepId() != null) {
							break;
						}
					}
					return s;
				} else if (s <= 0) {
					break;
				}
			}
		}
		return -1;
	}

	/**
	 * @see online.filter.RouteRequestFilter#getTargetPath(java.lang.String)
	 */
	@Override
	protected String getTargetPath(final String target) {
		return target + ".do";
	}
}
