package com.inspect.gateway.filter;

import java.util.Collections;
import java.util.List;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.OrderedGatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpMethod;
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
public class CacheRequestFilter extends AbstractGatewayFilterFactory<CacheRequestFilter.Config> {
    public CacheRequestFilter() {
        super(CacheRequestFilter.Config.class);
    }

    public String name() {
        return "CacheRequestFilter";
    }

    public GatewayFilter apply(CacheRequestFilter.Config config) {
        CacheRequestFilter.CacheRequestGatewayFilter cacheRequestGatewayFilter = new CacheRequestFilter.CacheRequestGatewayFilter();
        Integer order = config.getOrder();
        return (GatewayFilter) (order == null ? cacheRequestGatewayFilter : new OrderedGatewayFilter(cacheRequestGatewayFilter, order.intValue()));
    }

    public List<String> shortcutFieldOrder() {
        return Collections.singletonList("order");
    }

    static class Config {
        private Integer order;

        public Integer getOrder() {
            return this.order;
        }

        public void setOrder(Integer order) {
            this.order = order;
        }
    }

    public static class CacheRequestGatewayFilter implements GatewayFilter {
        public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
            HttpMethod method = exchange.getRequest().getMethod();
            return method != null && !method.matches("GET") && !method.matches("DELETE") ? DataBufferUtils.join(exchange.getRequest().getBody()).map((dataBuffer) -> {
                byte[] bytes = new byte[dataBuffer.readableByteCount()];
                dataBuffer.read(bytes);
                DataBufferUtils.release(dataBuffer);
                return bytes;
            }).defaultIfEmpty(new byte[0]).flatMap((bytes) -> {
                final DataBufferFactory dataBufferFactory = exchange.getResponse().bufferFactory();
                ServerHttpRequestDecorator decorator = new ServerHttpRequestDecorator(exchange.getRequest()) {
                    public Flux<DataBuffer> getBody() {
                        return bytes.length > 0 ? Flux.just(dataBufferFactory.wrap(bytes)) : Flux.empty();
                    }
                };
                return chain.filter(exchange.mutate().request(decorator).build());
            }) : chain.filter(exchange);
        }
    }
}
