package project.web.menu;

import java.io.IOException;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.config.ActionConfig;

import online.annotation.NoTransaction;
import online.filter.FilterUtil;
import online.filter.SessionAttributeFilter;
import online.struts.action.BrowseAction;
import online.struts.mapping.RequestMapping;

/**
 * 解放アクション
 *
 * @author Tadashi Nakayama
 * @version 1.0.0
 */
@NoTransaction
public final class ReleaseAction implements BrowseAction {

	/**
	 * @see online.struts.action.PerformAction#execute(
	 * org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm,
	 * javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	public ActionForward execute(final ActionMapping mapping,
			final ActionForm form, final HttpServletRequest request,
			final HttpServletResponse response) {

		final String val = request.getParameter("path");
		if (!Objects.toString(val, "").trim().isEmpty()) {
			final ActionConfig ac = mapping.getModuleConfig().findActionConfig("/" + val);
			if (RequestMapping.class.isInstance(ac)) {
				final RequestMapping rm = RequestMapping.class.cast(ac);
				// セション情報削除
				if (rm.getKeepId() != null && !rm.isMultipleKeep()) {
					SessionAttributeFilter.unbound(request, rm.getKeepId());
				}

				try {
					response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
					response.setHeader("Location",
							response.encodeRedirectURL(getLocation(val, request)));
					response.setContentLength(0);
					response.flushBuffer();
				} catch (final IOException ex) {
					LogManager.getLogger().info(ex.getMessage());
				}
				return null;
			}
		}

		try {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			response.flushBuffer();
		} catch (final IOException ex) {
			LogManager.getLogger().info(ex.getMessage());
		}
		return null;
	}

	/**
	 * Location取得
	 *
	 * @param str パス
	 * @param request リクエスト
	 * @return Location
	 */
	private String getLocation(final String str, final HttpServletRequest request) {
		final String uri = request.getRequestURI();
		final String qry = FilterUtil.stripParameter(request.getQueryString(), "path");
		final String ret = uri.substring(0, uri.lastIndexOf('/') + "/".length()) + str + ".do";
		return qry.isEmpty() ? ret : ret + "?" + qry;
	}
}
