package com.its.web.interceptor;

import com.its.web.service.common.CommonService;
import com.its.web.util.CommonUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;

@Slf4j
@RequiredArgsConstructor
public class ConnectHistory implements HandlerInterceptor {

    private final CommonService service;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String uri = request.getRequestURI();
        String[] ipAddressArr = new String[]{"127.0.0.1", "localhost", "220.122.218.208", "172.16.150.14"};
        HttpSession session = request.getSession();
        String hostIp = CommonUtil.getHttpServletRemoteIP(request);
        if (session.getAttribute(hostIp) == null && !uri.contains("/phits") && !uri.contains("error")) {
            LocalDateTime now = LocalDateTime.now();
            String formatNow = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

            log.info("Connect Ip Address : {}, UUID : {}, Connect Time : {}", hostIp, session.getId(), formatNow);
            session.setAttribute(hostIp, session.getId());
            try {
                service.insertConnHs();
            }
            catch (DataAccessException e) {
                log.error("방문자 카운팅에 실패하였습니다.");
            }
        }

        boolean isHostIp = Arrays.asList(ipAddressArr).contains(hostIp);
        String redirectPath = null;
        if (uri.contains("/phits")) {
            if (isHostIp) {
                Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                boolean isLogin = (authentication != null && !(authentication instanceof AnonymousAuthenticationToken) && authentication.isAuthenticated());

                if (isLogin && uri.equals("/phits")) {
                    redirectPath = "/phits/main";
                }
                if (!isLogin && !uri.equals("/phits")) {
                    redirectPath = "/phits";
                }

            }
            else {
                redirectPath = "/";
            }
        }

        if (redirectPath != null) {
            response.sendRedirect(redirectPath);
        }
        return true;
    }

}
