package com.style24.front.support.interceptor;

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

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

import com.style24.front.support.security.session.TsfSession;

import lombok.extern.slf4j.Slf4j;

/**
 * 로그인 체크 Interceptor
 * 
 * @author gagamel
 * @since 2020. 9. 11
 */
@Component
@Slf4j
public class TsfLoginCheckInterceptor extends HandlerInterceptorAdapter {

	@Value("${has-ssl}")
	private String hasSsl;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// 로그인 되어 있지 않으면
		if (!TsfSession.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
				// SSL Server
				boolean isSslServer = Boolean.parseBoolean(hasSsl);
				log.info("isSslServer: [{}]", isSslServer);

//				String loginUrl = isSslServer ? "https://" + request.getServerName() + "/signin" : "/signin";
				String loginUrl = "/signin";
				log.info("loginUrl: [{}]", loginUrl);

				response.sendRedirect(loginUrl);
//				response.flushBuffer();
			}

			return false;
		}

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

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

}
