package gaf3.core.gateway.filter.factory

import org.slf4j.LoggerFactory
import org.springframework.cloud.gateway.filter.GatewayFilter
import org.springframework.cloud.gateway.filter.OrderedGatewayFilter
import org.springframework.cloud.gateway.filter.RouteToRequestUrlFilter
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils
import java.net.URI

/**
 * @author dyg
 */
class ForwardGatewayFilterFactory : AbstractGatewayFilterFactory<ForwardGatewayFilterFactory.Config>(Config::class.java) {

    override fun shortcutFieldOrder(): List<String> {
        return arrayListOf(PATH_KEY, ORDER_KEY)
    }

    override fun apply(config: Config): GatewayFilter {
        return OrderedGatewayFilter({ exchange, chain ->
            // 提取Path
            val path = config.path ?: exchange.request.path
            val to = "forward://$path"
            val uri = URI(to)
            exchange.attributes[ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR] = uri
//            val exchange = exchange.mutate()
//                    .request(exchange.request.mutate().path(to).build())
//                    .build()

            log.debug("Forward to: {}", path)
            chain.filter(exchange)
        }, config.order)
    }

    class Config {
        var path: String? = null
        var order = RouteToRequestUrlFilter.ROUTE_TO_URL_FILTER_ORDER + 1
    }

    companion object {

        internal val log = LoggerFactory.getLogger(ForwardGatewayFilterFactory::class.java)

        const val PATH_KEY = "path"
        const val ORDER_KEY = "order"
    }
}
