package gaf3.core.gateway.bean

import org.slf4j.LoggerFactory
import org.springframework.cloud.gateway.filter.GlobalFilter
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.annotation.Order
import java.net.URI
import java.util.regex.Pattern

@Configuration
class GlobalFilterBean {
    //    @Bean
    //    @Order(-1)
    @Suppress("UseExpressionBody")
    fun hostToApp(): GlobalFilter {
        return GlobalFilter { exchange, chain ->
            log.debug("Set X-App use Host")
            val host = exchange.request.headers.getFirst("Host")
            //			host = exchange.getRequest().getHeaders().getFirst("X-Forwarded-Host");
            //			if(StringUtil.isNullOrEmpty(host))
            //				host = exchange.getRequest().getHeaders().getFirst("Host");
            val p = Pattern.compile("^([a-z0-9]+)\\.")
            val m = p.matcher(host!!.toLowerCase())
            if (!m.matches()) {
                return@GlobalFilter chain.filter(exchange.mutate().build())
            }
            var app : String = m.group(1)
            if (app !in arrayOf("hr", "wx", "plat")) {
                app = "www" // 默认应用
            }
            val request = exchange.request.mutate()
                    .headers { httpHeaders ->
                        httpHeaders[HEADER_APP] = app
                    }.build()
            log.debug("Set X-Tenant use Host: {}", app)
            chain.filter(exchange.mutate().request(request).build())
        }
    }

    @Bean
    @Order(-1)
    fun debugLog(): GlobalFilter {
        return GlobalFilter { exchange, chain ->
            val header = exchange.request.headers[HEADER_APP] ?: listOf("")
            val app1 = header[0]
            log.debug("[debug log] Host from header: {}", app1)
            val requestUrl = exchange.getRequiredAttribute<URI>(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR)
            log.debug("[debug log] Uri from exchange: {}", requestUrl)
            chain.filter(exchange)
        }
    }

    companion object {
        const val HEADER_APP = "X-App"
        internal val log = LoggerFactory.getLogger(GlobalFilterBean::class.java)
    }
}
