package com.storlead.framework.common.util;

import com.storlead.framework.common.properties.UrlChainDefinitionPorperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

/**
 * @program: sp-sales
 * @description:
 * @author: chenkq
 * @create: 2022-07-04 16:24
 */
@Component
public class UrlChainBlackAndWhiteUtil {
    @Autowired
    private UrlChainDefinitionPorperties properties;

    @Value("${server.servlet.context-path:}")
    private String servletContextPath;

    public String getContextPath() {
        if (servletContextPath != null && !servletContextPath.isEmpty()) {
            return servletContextPath;
        }
        return properties.getContextPath();
    }

    /**
     * 白名单URL
     * @param uri
     * @return
     */
    public boolean IsWhiteUri(String uri)
    {
        String [] AUTH_WHITELIST = properties.getAuthWhitelist();
        uri = normalizeRequestUri(uri);
        for (int i = 0; i < AUTH_WHITELIST.length; i++)
        {
            if (AUTH_WHITELIST[i].length() > 0)
            {
                String whiteuri = AUTH_WHITELIST[i];
                whiteuri = whiteuri.trim();
                AntPathMatcher antPathMatcher = new AntPathMatcher();
                boolean match = antPathMatcher.match(whiteuri,uri);
                if (match) {
                    return true;
                }
            }
        }
        return false;
    }

    private String normalizeRequestUri(String uri) {
        String ctx = getContextPath();
        if (ctx != null && !ctx.isEmpty() && !"/".equals(ctx) && uri.startsWith(ctx)) {
            uri = uri.substring(ctx.length());
        } else {
            uri = uri.replace(properties.getContextPath() + "/", "/");
        }
        if (!uri.startsWith("/")) {
            uri = "/" + uri;
        }
        return uri;
    }
}
