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


import com.eactive.eai.rms.common.login.LoginVo;
import com.eactive.eai.rms.common.login.SessionManager;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ClassUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

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


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


	@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);

	   if (isSkippable) {
	         valid = true;
	   } else if (loginVo != null) {
             SessionManager.setLoginVo(loginVo); // ThreadLocal에 설정
            
            // 이중 로그인 검사
           if (!SessionManager.isValidSession(request)) {
                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("/monitoring/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();
	}

}
