package com.style24.admin.support.interceptor;

import java.nio.charset.StandardCharsets;

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

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
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.biz.service.TsaSystemService;
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;

import com.gagaframework.web.util.GagaCookieUtil;

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

	@Autowired
	private TscMessageByLocale message;

	@Autowired
	private TsaSystemService systemService;

	@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 {
		// 쿠키로 설정된 메뉴ID
		String ckMenuId = GagaCookieUtil.getCookie(request, "CK_MENU_ID");
		log.info("ckMenuId: {}", ckMenuId);

		// 메뉴ID 쿠키가 있으면
		if (StringUtils.isNotBlank(ckMenuId)) {
			// Request URL with QueryString
			String reqUrl = request.getRequestURL().toString();
			if (StringUtils.isNotBlank(request.getQueryString())) {
				reqUrl += "?" + request.getQueryString();
			}

			// RequestBody는 request.getInputStream()을 통해 한 번만 읽을 수 있다.
			// Controller 또는 Interceptor에서 계속 액세스 하려면
			// JSON을 POJO 객체로 역직렬화 할 수 있도록 HttpServletRequestWrapper 확장해서 구현하고 TsaRequestFilter로 구성하여
			// TsaWebMvcConfig에 Filter를 등록한 후에 아래와 같이 가져오면 된다.
			String params = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8);
			log.info("params: {}", params);

			try {
				// 메뉴접속이력 생성
				systemService.createMenuAccessHistory(ckMenuId, reqUrl, (params.isEmpty() ? "" : params.toString()));
			} catch (Exception e) {
				// Do nothing
			}
		}
	}

}
