package com.inspect.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.inspect.base.core.utils.ServletUtils;
import com.inspect.base.core.utils.StringUtils;
import com.inspect.gateway.config.properties.CaptchaProperties;
import com.inspect.gateway.service.ValidateCodeService;

import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicReference;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

@Component
public class ValidateCodeFilter extends AbstractGatewayFilterFactory<Object> {
    private static final String[] VALIDATE_URL = new String[]{"/auth/login", "/auth/register"};
    private final ValidateCodeService validateCodeService;
    private final CaptchaProperties captchaProperties;
    private static final String CODE = "code";
    private static final String UUID = "uuid";

    public ValidateCodeFilter(ValidateCodeService validateCodeService, CaptchaProperties captchaProperties) {
        this.validateCodeService = validateCodeService;
        this.captchaProperties = captchaProperties;
    }

    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            if (StringUtils.containsAnyIgnoreCase(request.getURI().getPath(), VALIDATE_URL) && this.captchaProperties.getEnabled().booleanValue()) {
                try {
                    String rspStr = this.resolveBodyFromRequest(request);
                    JSONObject obj = JSONObject.parseObject(rspStr);
                    this.validateCodeService.checkCaptcha(obj.getString("code"), obj.getString("uuid"));
                } catch (Exception var6) {
                    return ServletUtils.webFluxResponseWriter(exchange.getResponse(), var6.getMessage());
                }

                return chain.filter(exchange);
            } else {
                return chain.filter(exchange);
            }
        };
    }

    private String resolveBodyFromRequest(ServerHttpRequest serverHttpRequest) {
        Flux<DataBuffer> body = serverHttpRequest.getBody();
        AtomicReference<String> bodyRef = new AtomicReference<>();
        body.subscribe((buffer) -> {
            CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer.asByteBuffer());
            DataBufferUtils.release(buffer);
            bodyRef.set(charBuffer.toString());
        });
        return bodyRef.get();
    }
}
