package com.eactive.eai.rms.common.interceptor;


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

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ClassUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.login.LoginVo;
import com.eactive.eai.rms.common.login.SessionManager;


public class SessionCheckInterceptor extends HandlerInterceptorAdapter {
	/**
	 * Logger for this class
	 */
	@SuppressWarnings("unused")
	private static final Logger logger = Logger
							.getLogger(SessionCheckInterceptor.class);

	@Autowired                                    
    private MonitoringContext monitoringContext;

	@Override
	public boolean preHandle(HttpServletRequest request,
							HttpServletResponse response, Object handler)
							throws Exception {

		boolean valid = false;

		LoginVo loginVo = SessionManager.getLoginVo(request);

		if (loginVo != null) {
			SessionManager.setLoginVo(loginVo);
		}

		org.springframework.web.method.HandlerMethod h = (org.springframework.web.method.HandlerMethod) handler;
		Class<?> clazz = h.getBeanType();
		
		//craft
	   boolean isSkippable = ClassUtils.isAssignable(clazz, InterceptorSkipController.class);
	   boolean isDualLogin = monitoringContext.getBooleanProperty(MonitoringContext.RMS_DUAL_LOGIN_ENABLED, true);

	   if (isSkippable) {
	         valid = true;
	   } else if (loginVo != null) {
             SessionManager.setLoginVo(loginVo); // ThreadLocal에 설정
            
            // 이중 로그인 검사
           if (!SessionManager.isValidSession(request, isDualLogin)) {
                logger.warn("Duplicate login detected for user: " + loginVo.getUserId());
                valid = false;  
            } else {
                String roleId = SessionManager.getRoleIdString(request);
                String userName = SessionManager.getUserName(request);
                valid = StringUtils.isNotBlank(roleId) && StringUtils.isNotBlank(userName);
            }
	    }
	   
	   // if (request.getSession().getAttribute("redirectInProgress") != null) {
	   //     return true; // 이미 리다이렉트 중이면 추가 리다이렉트 방지
	   // }

		if (!valid) {
			if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
				response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//				response.setContentType("application/json;charset=UTF-8");
			} else {
				//request.getRequestDispatcher("/monitoring/loginForm.do").forward(request, response);
				//request.getSession().setAttribute("redirectInProgress", true);
				response.sendRedirect(request.getContextPath() + "/rms/logout.do");
				//response.sendRedirect("/monitoring/loginForm.do");

			}
		}

		return valid;

	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		SessionManager.clearLoginVo();
	}

}
