package gaf3.core.gateway.webfilter

import org.slf4j.LoggerFactory
import org.springframework.web.server.ServerWebExchange
import org.springframework.web.server.WebFilter
import org.springframework.web.server.WebFilterChain
import reactor.core.publisher.Mono
import gaf3.core.gateway.bean.GlobalFilterBean
import java.util.regex.Pattern

class HostToAppFilter: WebFilter {
    override fun filter(exchange: ServerWebExchange, chain: WebFilterChain) : Mono<Void>{
        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]+)\\.smart.*")
        val m = p.matcher(host!!.toLowerCase())
        if (!m.matches()) {
            log.debug("Not matches: {}", host.toLowerCase())
            return chain.filter(exchange.mutate().build())
        }
        var app : String = m.group(1)
        if (app !in arrayOf("hr", "wx", "plat")) {
            app = "www" // 默认应用
        }
        exchange.attributes[GlobalFilterBean.HEADER_APP] = app

        val request = exchange.request.mutate()
                .headers { httpHeaders ->
                    httpHeaders[GlobalFilterBean.HEADER_APP] = app
                }.build()
        log.debug("Set X-Tenant : {}", app)
        return chain.filter(exchange.mutate().request(request).build())
    }

    companion object {
        internal val log = LoggerFactory.getLogger(HostToAppFilter::class.java)
    }

}
