package egovframework.interceptors;

import egovframework.service.impl.CommonServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Slf4j
//@RequiredArgsConstructor
public class LogAdapterInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private CommonServiceImpl 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) {
        //TODO 문제점 쿠키를 사용하면 한번 접속한사람은 쿠키를 지우기전까지 접속횟수가 안오름
        //지금에러나는 이유는 디비에 url이 안맞아서 에러나는거임

        String requestUri = request.getRequestURI();
        String requestAction = requestUri.substring(requestUri.lastIndexOf("/") + 1);
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("uri", requestAction);
        String maxAge = request.getParameter("maxAge");
        if (maxAge == null || "".equals(maxAge)) {
            maxAge = "3600";
        }

//		System.out.println("requestAction = " + requestAction);

        maxAge = maxAge.replaceAll("\r", "");
        int t = Integer.parseInt(maxAge);
        if (t > 3600) {
            t = 3600;
        }

        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(t);
            cookie.setSecure(true);
            cookie.setPath("/");
            response.addCookie(cookie);
            this.commonService.insertUpdateLogWeb(paramMap);
        }
    }

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

}
