package com.persagy.bdtp.adm.datatx;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.persagy.bdtp.adm.common.AdmRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;

/**
 * 数据传输帮助类
 */
@Component
public class DataTxHandler {

	private final ObjectMapper objectMapper;

	@Autowired
	public DataTxHandler(ObjectMapper objectMapper) {
		this.objectMapper = objectMapper;
	}

	/**
	 * 处理上传请求的gzip压缩数据
	 */
	public AdmRequest handleRequest(HttpServletRequest req) {
		try {
			InputStream in = req.getInputStream();
			String contentEncoding = req.getHeader("Content-Encoding");
			if (contentEncoding != null && contentEncoding.indexOf("gzip") >= 0) {
				GZIPInputStream gzipInputStream = new GZIPInputStream(in);
				in = gzipInputStream;
			}

			ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int n;
			while ((n = in.read(buffer)) >= 0) {
				out.write(buffer, 0, n);
			}

			String json = new String(out.toByteArray(), "UTF-8");
			return objectMapper.readValue(json, AdmRequest.class);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

}
