package net.waltzstudio.montecarlo.interceptor;

import static net.waltzstudio.base.framework.util.SyntaxSugar.*;
import java.util.Map;
import javax.annotation.Resource;
import org.aopalliance.intercept.MethodInvocation;
import org.seasar.framework.aop.interceptors.AbstractInterceptor;
import org.seasar.framework.util.StringUtil;
import net.waltzstudio.base.framework.util.BaseUtil;
import net.waltzstudio.montecarlo.dto.SessionInfoDto;
import net.waltzstudio.montecarlo.object.Global;
import net.waltzstudio.montecarlo.service.LoginService;

/**
 * ログインInterceptor
 */
public class LoginInterceptor extends AbstractInterceptor {
	private static final long serialVersionUID = 1L;

	/** リクエスト */
	@Resource
	protected Map<String, Object> requestScope;
	/** セッション */
	@Resource
	protected Map<String, Object> sessionScope;
	/** セッション情報 */
	@Resource
	protected SessionInfoDto sessionInfoDto;
	/** ログインService */
	@Resource
	protected LoginService loginService;

	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		if (loginService.isLoggedIn(invocation)) {
			if (!loginService.checkProjectCode()) {
				BaseUtil.sendError(403);
				return null;
			}
			loginService.setRequestInfo();
			return invocation.proceed();
		} else {
			String redirectUrl = S(requestScope.get(Global.RequestInfo.SERVLET_PATH));
			if (!StringUtil.isEmpty(S(requestScope.get(Global.RequestInfo.QUERY_STRING)))) {
				redirectUrl = S(redirectUrl, "?", requestScope.get(Global.RequestInfo.QUERY_STRING));
			}
			sessionScope.put(Global.SessionInfo.REDIRECT_URL, redirectUrl);
			return "/secure?redirect=true";
		}
	}

}
