/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved. <a>http://www.crunii.com</a>
 */
package com.crunii.micro.gateway.filter.web.dt;

import java.io.ByteArrayOutputStream;
import java.nio.channels.Channels;
import java.nio.charset.StandardCharsets;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;

import com.crunii.micro.common.utils.BusiLogUtil;

import reactor.core.publisher.Flux;

/**
 * @author 田平 create 2021年1月12日下午3:38:03
 */
public class RequestLoggingDecorator extends ServerHttpRequestDecorator {

	public static final String REQ_BODY_KEY = RequestLoggingDecorator.class.getName() + ".req.body.key";

	private Map<String, Object> attributes;

	public RequestLoggingDecorator(ServerHttpRequest delegate, Map<String, Object> attributes) {
		super(delegate);
		this.attributes = attributes;
	}

	@Override
	public Flux<DataBuffer> getBody() {
		if (BusiLogUtil.checkContentType(getHeaders().getContentType())) {
			ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
			return super.getBody().doOnNext(dataBuffer -> {
				try {
					Channels.newChannel(baos).write(dataBuffer.asByteBuffer().asReadOnlyBuffer());
					String reqBody = new String(baos.toByteArray(), StandardCharsets.UTF_8);
					attributes.put(REQ_BODY_KEY, reqBody);
				} catch (Exception e) {
					throw new RuntimeException(e);
				} finally {
					IOUtils.closeQuietly(baos);
				}
			});
		} else {
			return super.getBody();
		}
	}
}
