package gaf3.core.gateway.filter.factory

import org.springframework.cloud.gateway.filter.GatewayFilter
import org.springframework.cloud.gateway.filter.GatewayFilterChain
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils.URI_TEMPLATE_VARIABLES_ATTRIBUTE
import org.springframework.web.server.ServerWebExchange
import org.springframework.web.util.UriTemplate
import org.springframework.web.util.pattern.PathPattern

/**
 * @author dyg
 */
class SetRequestHeaderExGatewayFilterFactory : AbstractNameValueGatewayFilterFactory() {

    override fun apply(config: NameValueConfig): GatewayFilter {
        return GatewayFilter { exchange: ServerWebExchange, chain: GatewayFilterChain ->
            val uriTemplate = UriTemplate(config.value)

            val variables: PathPattern.PathMatchInfo? = exchange.getAttribute(URI_TEMPLATE_VARIABLES_ATTRIBUTE)
            val uriVariables: Map<String, String>

            if (variables != null) {
                uriVariables = variables.uriVariables
            } else {
                uriVariables = emptyMap()
            }

            val uri = uriTemplate.expand(uriVariables)
            val newPath = uri.rawPath

            val request = exchange.request.mutate()
                    .headers { httpHeaders -> if (newPath != null) httpHeaders[config.name] = newPath }
                    .build()

            chain.filter(exchange.mutate().request(request).build())
        }
    }
}
