package ink.wgink.gateway.filter.local;

import ink.wgink.gateway.consts.ISystemConst;
import ink.wgink.gateway.pojo.route.Route;
import org.springframework.cloud.gateway.filter.FilterDefinition;
import org.springframework.cloud.gateway.filter.factory.RewriteLocationResponseHeaderGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.factory.RewritePathGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.factory.RewriteResponseHeaderGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.factory.SetPathGatewayFilterFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: CommonFilters
 * @Description: 通用过滤器
 * @Author: WangGeng
 * @Date: 2021/4/24 20:31
 * @Version: 1.0
 **/
public class CommonFiltersDefinition {

    /**
     * 重写过滤器，将路径中的gw删除，暂时无用
     *
     * @param route
     * @return
     */
    public FilterDefinition rewritePath(Route route) {
        FilterDefinition rewritePath = new FilterDefinition();
        Map<String, String> rewritePathMap = new HashMap<>(4);
        rewritePathMap.put(RewritePathGatewayFilterFactory.REGEXP_KEY, ISystemConst.ROUTE_PREFIX + "/?(?<segment>.*)");
        rewritePathMap.put(RewritePathGatewayFilterFactory.REPLACEMENT_KEY, "/$\\{segment}");
        rewritePath.setArgs(rewritePathMap);
        rewritePath.setName("RewritePath");
        return rewritePath;
    }

    /**
     * 设置路径过滤器
     *
     * @param route
     * @return
     */
    public FilterDefinition setPath(Route route) {
        FilterDefinition setPath = new FilterDefinition();
        Map<String, String> setPathMap = new HashMap<>(2);
        setPathMap.put(SetPathGatewayFilterFactory.TEMPLATE_KEY, route.getSetPath());
        setPath.setArgs(setPathMap);
        setPath.setName("SetPath");
        return setPath;
    }

    /**
     * 重写响应头中的地址信息
     *
     * @param route
     * @return
     */
    public FilterDefinition rewriteLocationResponseHeader(Route route) {
        FilterDefinition rewriteLocationResponse = new FilterDefinition();
        Map<String, String> rewriteLocationResponseMap = new HashMap<>(2);
        rewriteLocationResponseMap.put("stripVersionMode", RewriteLocationResponseHeaderGatewayFilterFactory.StripVersion.AS_IN_REQUEST.toString());
        rewriteLocationResponseMap.put("hostValue", "Location");
        rewriteLocationResponse.setName("RewriteLocationResponseHeader");
        return rewriteLocationResponse;
    }

}
