package com.qingyun.framework.encrypt.advice;


import cn.hutool.crypto.SecureUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

@Slf4j
public class DecryptHttpInputMessage implements HttpInputMessage {

	private HttpHeaders headers;
	private InputStream body;


	public DecryptHttpInputMessage(HttpInputMessage inputMessage, String aesKey, boolean showLog) throws Exception {

		this.headers = inputMessage.getHeaders();
		String content = new BufferedReader(new InputStreamReader(inputMessage.getBody()))
			.lines().collect(Collectors.joining(System.lineSeparator()));
		String decryptBody = "";
		if (content.startsWith("{")) {
			log.info("原内容:{}", content);
			decryptBody = content;
		} else {
			content = content.replaceAll(" ", "+");
			if (StringUtils.isNotEmpty(content)) {
				decryptBody = SecureUtil.aes(aesKey.getBytes()).decryptStr(content);
			}
			if (showLog) {
				log.info("原内容：{},解析结果：{}", content, decryptBody);
			}
		}
		this.body = new ByteArrayInputStream(decryptBody.getBytes());
	}

	@Override
	public InputStream getBody() {
		return body;
	}

	@Override
	public HttpHeaders getHeaders() {
		return headers;
	}
}
