package com.yonge.cooleshow.auth.config;

import com.vdurmont.emoji.EmojiParser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.StreamUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

public class ParameterCheckServletRequestWrapper extends HttpServletRequestWrapper {

	private byte[] requestBody;
	private Charset charSet;

	public ParameterCheckServletRequestWrapper(HttpServletRequest request) throws IOException {
		super(request);

		String requestBodyStr = getRequestPostStr(request);
		if (StringUtils.isNotBlank(requestBodyStr)) {
			requestBodyStr = EmojiParser.removeAllEmojis(requestBodyStr);
			requestBody = requestBodyStr.getBytes(charSet);
		} else {
			requestBody = new byte[0];
		}
	}

	public String getRequestPostStr(HttpServletRequest request) throws IOException {
		String charSetStr = request.getCharacterEncoding();
		if (charSetStr == null) {
			charSetStr = "UTF-8";
		}
		charSet = Charset.forName(charSetStr);

		return StreamUtils.copyToString(request.getInputStream(), charSet);
	}

	/**
	 * 重写 getInputStream()
	 */
	@Override
	public ServletInputStream getInputStream() {
		if (requestBody == null) {
			requestBody = new byte[0];
		}

		final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(requestBody);

		return new ServletInputStream() {
			@Override
			public boolean isFinished() {
				return false;
			}

			@Override
			public boolean isReady() {
				return false;
			}

			@Override
			public void setReadListener(ReadListener readListener) {

			}

			@Override
			public int read() {
				return byteArrayInputStream.read();
			}
		};
	}

	/**
	 * 重写 getReader()
	 */
	@Override
	public BufferedReader getReader() {
		return new BufferedReader(new InputStreamReader(getInputStream()));
	}

}
