package com.style24.admin.support.readable;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.io.IOUtils;

/**
 * RequestBody는 request.getInputStream()을 통해 한 번만 읽을 수 있다.
 * Controller 또는 Interceptor에서 계속 액세스 하기 위해 JSON을 POJO 객체로 역직렬화 할 수 있도록 구현한 HttpServletRequestWrapper
 * 
 * @author gagamel
 * @since 2021. 4. 20
 */
public class TsaHttpServletRequestWrapper extends HttpServletRequestWrapper {

	private byte[] rawData = {};
	private HttpServletRequest request;
	private TsaServletInputStream servletStream;

	public TsaHttpServletRequestWrapper(HttpServletRequest request) {
		super(request);
		this.request = request;
		this.servletStream = new TsaServletInputStream();
	}

	public void resetInputStream() throws IOException {
		initRawData();
		servletStream.inputStream = new ByteArrayInputStream(rawData);
	}

	private void initRawData() throws IOException {
		if (rawData.length == 0) {
			byte[] b = IOUtils.toByteArray(this.request.getInputStream());
			if (b != null)
				rawData = b;
		}

		servletStream.inputStream = new ByteArrayInputStream(rawData);
	}

	@Override
	public ServletInputStream getInputStream() throws IOException {
		initRawData();
		return servletStream;
	}

	public BufferedReader getReader() throws IOException {
		initRawData();
		String encoding = getCharacterEncoding();
		if (encoding != null) {
			return new BufferedReader(new InputStreamReader(servletStream, encoding));
		} else {
			return new BufferedReader(new InputStreamReader(servletStream));
		}
	}

}
