package com.its.web.interceptor;

import com.its.web.service.common.CommonService;
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.net.InetAddress;
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 Exception {
        InetAddress ipAddress = InetAddress.getLocalHost();
        String hostIp = ipAddress.getHostAddress();
        String uri = request.getRequestURI();
        String[] ipAddressArr = new String[]{"127.0.0.1", "localhost", "192.168.20.46"};
        HttpSession session = request.getSession();
        if (session.getAttribute(hostIp) == null && !uri.contains("/phits")) {
            log.info("Connect Ip Address : {}, UUID : {}", hostIp, session.getId());
            session.setAttribute(hostIp, session.getId());
            try {
                service.insertConnHs();
            }
            catch (DataAccessException e) {
                log.error("접속 이력 등록에 실패하였습니다.");
            }
        }
        if (uri.equals("/phits")) {
            if (Arrays.asList(ipAddressArr).contains(hostIp)) {
                Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken) && authentication.isAuthenticated()) {
                    response.sendRedirect("/phits/main");
                }
                return true;
            }
            response.sendRedirect("/");
        }

        return true;
    }
}
