package gaf3.core.gateway.filter.factory

import gaf3.core.exception.BusinessError
import gaf3.core.services.verify.service.VerifyCodeService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.configurationprocessor.json.JSONObject
import org.springframework.cloud.gateway.filter.GatewayFilter
import org.springframework.cloud.gateway.filter.OrderedGatewayFilter
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory
import org.springframework.http.HttpStatus
import reactor.core.publisher.Mono
import java.awt.image.DataBuffer
import java.nio.charset.StandardCharsets

class VerifyCodeGatewayFilterFactory(@Autowired val service: VerifyCodeService) : AbstractGatewayFilterFactory<VerifyCodeGatewayFilterFactory.Config>(Config::class.java) {

    override fun apply(config: Config): GatewayFilter {
        return OrderedGatewayFilter({ exchange, chain ->
            val queryParams = exchange.request.queryParams
            val state = queryParams["state"]?.firstOrNull()
            val code = queryParams["code"]?.firstOrNull()
            if(state.isNullOrBlank() || code.isNullOrBlank() || !service.verify(state, code)) {
                exchange.response.statusCode = HttpStatus.OK
                var msg = JSONObject()
                msg.put("errcode", BusinessError.ERR_VERIFYCODE_INVALID)
                msg.put("errmsg", "验证码无效")
                var bits: ByteArray = msg.toString().toByteArray(StandardCharsets.UTF_8)
                var buffer = exchange.response.bufferFactory().wrap(bits)
                exchange.response.headers.add("Content-Type", "application/json;charset=UTF-8")
                exchange.response.setStatusCode(HttpStatus.BAD_REQUEST)
                exchange.response.writeWith(Mono.just(buffer))
                // exchange.response.setComplete()
            }else
                chain.filter(exchange)
        }, config.order)
    }

    class Config {
        var order: Int = 0
    }
}