package egovframework.com.its.web.server.interceptors;

import egovframework.com.its.web.server.service.CommonService;
import egovframework.com.its.web.server.util.IpCheck;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
//@RequiredArgsConstructor
@Component
public class LogAdapterInterceptor implements HandlerInterceptor {

    @Autowired
    private CommonService commonService;

//	@Override
//	public void afterCompletion(HttpServletRequest request,
//			HttpServletResponse response, Object arg2, Exception arg3)
//			throws Exception {
//	}

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3) {
        boolean isStatistics = true;
        Map<String, Object> paramMap = new HashMap<>();
        String requestUri = request.getRequestURI();

        String requestAction = requestUri.substring(requestUri.lastIndexOf("/") + 1);
        if (requestAction.contains(";")) {
            requestAction = requestAction.substring(0, requestAction.indexOf(";"));
        }
        // 세션정보가 메뉴별로 저장됨(서버리소스 부담...)
        String attrMenuId = "id_" + requestAction;
        String attrMenuTm = "tm_" + requestAction;
        //String attrMenuId = "last_access_menu";
        //String attrMenuTm = "last_access_time";


        int sessionTimeoutSec = 30*60;
        HttpSession session = request.getSession(true);
        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        log.info("sessionId = {}", session.getId());
//        log.info("maxInactiveInterval = {}", session.getMaxInactiveInterval());
//        log.info("creationTime = {}", sdfDate.format(new Date(session.getCreationTime())));
//        log.info("lastAccessedTime = {}", sdfDate.format(new Date(session.getLastAccessedTime())));
//        log.info("isNew = {}", session.isNew());
//        log.info("attrMenuId = {}", attrMenuId);
//        log.info("attrMenuTm = {}", attrMenuTm);

        Integer menuClickCount = (Integer)session.getAttribute(attrMenuId);
        Long menuAccessTime = (Long)session.getAttribute(attrMenuTm);
        Long currentTime = new Date().getTime();

        if (menuClickCount == null || menuAccessTime == null || (currentTime - menuAccessTime) > sessionTimeoutSec*1000) {
            // 처음으로 로그인 하거나 유효시간이 지났음.
            menuClickCount = 0;
        } else {
            // 유효기간 내에 재 방문하였음.
            isStatistics = false;
        }

        menuClickCount++;
        session.setAttribute(attrMenuId, menuClickCount);
        session.setAttribute(attrMenuTm, currentTime);
        String userAgent = request.getHeader("User-Agent");
        if (isStatistics && !(userAgent.contains("python-requests/2.27.1") || userAgent.replace("Mozilla/5.0", "").isEmpty())) {
            paramMap.put("uri", requestAction);
            // 디비 저장
            this.commonService.addUpdateLogWeb(paramMap);
        }
//
//        String requestUri = request.getRequestURI();
//        String requestAction = requestUri.substring(requestUri.lastIndexOf("/") + 1);
//        Map<String, Object> paramMap = new HashMap<String, Object>();
//        paramMap.put("uri", requestAction);
//
//        Cookie cookie = null;
//        Cookie cookies[] = request.getCookies();
//
//        if (cookies != null) {
//            HashMap<String, Object> mapCookie = new HashMap<String, Object>();
//            for (int i = 0; i < cookies.length; i++) {
//                Cookie obj = cookies[i];
//                if (obj.getName().equals(requestAction)) {
//                    mapCookie.put(obj.getName(), obj.getValue());
//                    break;
//                }
//            }
//
//            if (mapCookie.get(requestAction) == null) {
//                cookie = new Cookie(requestAction, requestAction);
//            } else {
//                if (!mapCookie.get(requestAction).equals(requestAction)) {
//                    cookie = new Cookie(requestAction, requestAction);
//                }
//            }
//        } else {
//            cookie = new Cookie(requestAction, requestAction);
//        }
//
//        if (cookie != null) {
//            cookie.setMaxAge(60*60);
//            cookie.setSecure(true);
//            cookie.setPath("/");
//            response.addCookie(cookie);
//            this.commonService.insertUpdateLogWeb(paramMap);
//        }
    }

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) {
        //log.error("{}, {}", request.getMethod(), request.getRequestURI());
		return true;
	}

}
