package org.springblade.common.interceptor;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springblade.common.utils.IpUtils;
import org.springblade.core.tool.api.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import org.springframework.util.AntPathMatcher;

@Slf4j
public class WhiteListHandlerInterceptor implements HandlerInterceptor {

    @Autowired
    private WhiteConfigEntity ipWhiteConfig;

    private final AntPathMatcher pathMatcher;

    public WhiteListHandlerInterceptor(AntPathMatcher pathMatcher) {
        this.pathMatcher = pathMatcher;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //log.info("WhiteListHandlerInterceptor ipWhiteConfig:{}, ", ipWhiteConfig.toString());
        if (!ipWhiteConfig.isEnable()) {
            return true;
        }
        String currentUrl = request.getRequestURI();
        String ipAddr = IpUtils.getIpAddr(request);
        log.info("WhiteListHandlerInterceptor currentUrl:{}, ipAddr:{}", currentUrl, ipAddr);
        if(CollectionUtil.isEmpty(ipWhiteConfig.getUrlList()) || StringUtils.isBlank(currentUrl)){
            return true;
        }
        if(this.isUrlInWhiteList(currentUrl, ipWhiteConfig.getUrlList()) != true){
            return true;
        }
        if(CollectionUtil.isEmpty(ipWhiteConfig.getIpWhiteList()) || StringUtils.isBlank(ipAddr)){
            return true;
        }
        if (ipWhiteConfig.getIpWhiteList().contains(ipAddr)) {
            return true;
        } else {
            log.info("该IP不在允许访问白名单内, ipWhiteList:{}, urlList:{}", ipWhiteConfig.getIpWhiteList().toString(), ipWhiteConfig.getUrlList().toString());
            result(response, JSONObject.toJSONString(R.fail("该IP不在允许访问白名单内")));
            return false;
        }
    }


    /**
     * 判断地址是否在白名单中
     * @param url
     * @param whitelistPatterns
     * @return boolean
     */
    public boolean isUrlInWhiteList(String url, List<String> whitelistPatterns) {
        for (String pattern : whitelistPatterns) {
            if (pathMatcher.match(pattern, url)) {
                return true;
            }
        }
        return false;
    }


    private void result(HttpServletResponse response, String result) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.println(result);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
