package com.dbnt.faisp.config;

import com.dbnt.faisp.main.userInfo.model.UserAlarm;
import com.dbnt.faisp.main.userInfo.model.UserRequestLog;
import com.dbnt.faisp.main.userInfo.service.UserAlarmService;
import com.dbnt.faisp.main.userInfo.service.UserLogService;
import com.dbnt.faisp.util.Utils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

@Component
@RequiredArgsConstructor
public class FaispInterceptor implements HandlerInterceptor {

  private final UserLogService userLogService;
  private final UserAlarmService userAlarmService;

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView mav) throws Exception {
    if (mav!=null){
      String xReq = request.getHeader("X-Requested-With");
      if(xReq == null || !xReq.equals("XMLHttpRequest")){
        // mav가 있으면서 ajax요청이 아닐 때 알람 조회.
        UserAlarm param = new UserAlarm();
        param.setUserSeq((Integer) request.getSession().getAttribute("userSeq"));
        param.setViewYn("N");
        param.setQueryInfo();
        mav.addObject("alarmList", userAlarmService.selectAlarmList(param));
      }
    }
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    //페이지 렌더링 후 실행.
    UserRequestLog log = new UserRequestLog();
    log.setContactIp(Utils.getClientIP(request));
    log.setRequestUrl(request.getRequestURI());
    log.setRequestMethod(request.getMethod());
    log.setSearchParams(request.getQueryString());
    log.setHandlerDescription(((HandlerMethod) handler).toString());
    log.setUserOrgan((String) request.getSession().getAttribute("userOrgan"));
    log.setUserBelong((String) request.getSession().getAttribute("belongValue"));
    userLogService.saveRequestLog(log);
  }
}
