package com.style24.admin.support.interceptor;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.style24.admin.support.security.session.TsaSession;
import com.style24.core.support.exception.TscNoSessionException;
import com.style24.core.support.message.TscMessageByLocale;

import lombok.extern.slf4j.Slf4j;

/**
 * 모든 Request에 대해 세션 확인
 * 
 * @author gagamel
 * @since 2020. 10. 5
 */
@Component
@Slf4j
public class TsaDefaultInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private TscMessageByLocale message;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		log.info("request.isSecure(): [{}]", request.isSecure());
		log.info("request.getServerName(): [{}]", request.getServerName());
		log.info("request.getRequestURI(): [{}]", request.getRequestURI());
		log.info("request.getRequestURL(): [{}]", request.getRequestURL());
		log.info("request.getQueryString(): [{}]", request.getQueryString());

		boolean isLogin = TsaSession.isLogin();
		log.info("isLogin: [{}]", isLogin);

		if (!isLogin) {
			boolean isAjaxCall = Boolean.parseBoolean(request.getHeader("AJAX"));
			log.info("isAjaxCall: {}", isAjaxCall);

			if (isAjaxCall) { // ajax call
				// Ajax call은 status 세팅 후 ajax.status == 901일 경우 로그인 페이지로 이동 처리
				response.setStatus(901); // No Session
			} else { // Submit
				throw new TscNoSessionException(message.getMessage("LOGN_0003"));
			}

			return false;
		}

		return super.preHandle(request, response, handler);
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
		ModelAndView modelAndView) throws Exception {
		// Do nothing
	}

}
