package com.inspect.gateway.filter;

import com.inspect.base.core.utils.ServletUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;

@Component
public class BlackListUrlFilter extends AbstractGatewayFilterFactory<BlackListUrlFilter.Config> {
    public GatewayFilter apply(BlackListUrlFilter.Config config) {
        return (exchange, chain) -> {
            String url = exchange.getRequest().getURI().getPath();
            return config.matchBlacklist(url) ? ServletUtils.webFluxResponseWriter(exchange.getResponse(), "请求地址不允许访问") : chain.filter(exchange);
        };
    }

    public BlackListUrlFilter() {
        super(BlackListUrlFilter.Config.class);
    }

    public static class Config {
        private List<String> blacklistUrl;
        private List<Pattern> blacklistUrlPattern = new ArrayList<>();

        public boolean matchBlacklist(String url) {
            return !this.blacklistUrlPattern.isEmpty() && this.blacklistUrlPattern.stream().anyMatch((p) -> {
                return p.matcher(url).find();
            });
        }

        public List<String> getBlacklistUrl() {
            return this.blacklistUrl;
        }

        public void setBlacklistUrl(List<String> blacklistUrl) {
            this.blacklistUrl = blacklistUrl;
            this.blacklistUrlPattern.clear();
            this.blacklistUrl.forEach((url) -> {
                this.blacklistUrlPattern.add(Pattern.compile(url.replaceAll("\\*\\*", "(.*?)"), 2));
            });
        }
    }
}
