/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved.
 * <a>http://www.crunii.com</a>
 */
package com.crunii.micro.gateway.filter;

import com.crunii.micro.gateway.swagger.SwaggerProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.gateway.filter.headers.HttpHeadersFilter;
import org.springframework.cloud.gateway.filter.headers.XForwardedHeadersFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 田平 create 2021/7/9 16:58
 */
@Component
@ConditionalOnProperty(name = "swagger.enabled", havingValue = "true")
public class SwaggerHeaderFilter implements HttpHeadersFilter, Ordered {

	@Value("${spring.cloud.gateway.prefix:/api}")
	private String prefix;

	@Value("${spring.cloud.gateway.enablePrefix:false}")
	private boolean enablePrefix;

	@Override
	public int getOrder() {
		return Ordered.LOWEST_PRECEDENCE;
	}

	@Override
	public HttpHeaders filter(HttpHeaders input, ServerWebExchange exchange) {
		String path = exchange.getRequest().getURI().getRawPath();
		if (path.endsWith(SwaggerProvider.SWAGGER2URL)) {
			//修改代理前缀，添加网关的prefix
			List<String> preValues = input.remove(XForwardedHeadersFilter.X_FORWARDED_PREFIX_HEADER);
			if (preValues != null && !preValues.isEmpty()) {
				String newValues = preValues.stream().collect(Collectors.joining());
				String headerPrefixValue = null;
				if (enablePrefix) {
					headerPrefixValue = prefix + newValues;
				} else {
					headerPrefixValue = newValues;
				}
				input.add(XForwardedHeadersFilter.X_FORWARDED_PREFIX_HEADER, headerPrefixValue);
			} else {
				if (enablePrefix) {
					input.add(XForwardedHeadersFilter.X_FORWARDED_PREFIX_HEADER, prefix);
				}
			}
		}
		return input;
	}

}
