package com.inspect.gateway.filter;

import com.inspect.base.core.utils.StringUtils;
import com.inspect.base.core.utils.html.EscapeUtil;
import com.inspect.gateway.config.properties.XssProperties;
import io.netty.buffer.ByteBufAllocator;

import java.nio.charset.StandardCharsets;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Component
@ConditionalOnProperty(
        value = {"security.xss.enabled"},
        havingValue = "true"
)
public class XssFilter implements GlobalFilter, Ordered {
    private final XssProperties xss;

    public XssFilter(XssProperties xss) {
        this.xss = xss;
    }

    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        HttpMethod method = request.getMethod();
        if (method != null && !method.matches("GET") && !method.matches("DELETE")) {
            if (!this.isJsonRequest(exchange)) {
                return chain.filter(exchange);
            } else {
                String url = request.getURI().getPath();
                if (StringUtils.matches(url, this.xss.getExcludeUrls())) {
                    return chain.filter(exchange);
                } else {
                    ServerHttpRequestDecorator httpRequestDecorator = this.requestDecorator(exchange);
                    return chain.filter(exchange.mutate().request(httpRequestDecorator).build());
                }
            }
        } else {
            return chain.filter(exchange);
        }
    }

    private ServerHttpRequestDecorator requestDecorator(ServerWebExchange exchange) {
        ServerHttpRequestDecorator serverHttpRequestDecorator = new ServerHttpRequestDecorator(exchange.getRequest()) {
            public Flux<DataBuffer> getBody() {
                Flux<DataBuffer> body = super.getBody();
                return body.buffer().map((dataBuffers) -> {
                    DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                    DataBuffer join = dataBufferFactory.join(dataBuffers);
                    byte[] content = new byte[join.readableByteCount()];
                    join.read(content);
                    DataBufferUtils.release(join);
                    String bodyStr = new String(content, StandardCharsets.UTF_8);
                    bodyStr = EscapeUtil.clean(bodyStr);
                    byte[] bytes = bodyStr.getBytes();
                    NettyDataBufferFactory nettyDataBufferFactory = new NettyDataBufferFactory(ByteBufAllocator.DEFAULT);
                    DataBuffer buffer = nettyDataBufferFactory.allocateBuffer(bytes.length);
                    buffer.write(bytes);
                    return buffer;
                });
            }

            public HttpHeaders getHeaders() {
                HttpHeaders httpHeaders = new HttpHeaders();
                httpHeaders.putAll(super.getHeaders());
                httpHeaders.remove("Content-Length");
                httpHeaders.set("Transfer-Encoding", "chunked");
                return httpHeaders;
            }
        };
        return serverHttpRequestDecorator;
    }

    public boolean isJsonRequest(ServerWebExchange exchange) {
        String header = exchange.getRequest().getHeaders().getFirst("Content-Type");
        return StringUtils.startsWithIgnoreCase(header, "application/json");
    }

    public int getOrder() {
        return -100;
    }
}
