package com.springbank.base.sockethandler;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author wangxin
 * @contact 408657544@qq.com
 * @date Jul 14, 2017
 * @Description: 处理客户端socket的输入输出流
 */
public class SocketStreamHandler {
	
	/** 来报报文中报文头的长度,所谓报文头,是指比如前面8位是00000158,这样的报文头,表示随后的158个字节是实际报文内容 */
	private int inputHeaderLength;
	/** 返回报文报文头长度位位数 */
	private int outputHeaderLength;
	/** 来报报文编码 */
	private String encoding;
	private final Logger log = LoggerFactory.getLogger(getClass());
	
	/** 读inputStream,将读出的字节数组返回 
	 * @throws IOException */
	public byte[] readStream(InputStream inputStream) throws IOException {
		
		//读出长度
		byte[] headBytes = new byte[inputHeaderLength];
		inputStream.read(headBytes);
		log.debug("head lengh: "+new String(headBytes));
		
		//读出报文
		byte[] bodyBytes = new byte[Integer.parseInt(new String(headBytes))];
		inputStream.read(bodyBytes, 0, bodyBytes.length);
		
		log.debug("recv: " + new String(headBytes,encoding) + new String(bodyBytes,encoding));
		return bodyBytes;
	}
	
	//报文流输出
	//2017.07.17 返回报文时增加8位长度位报文头
	public void writeStream(byte[] bytes, OutputStream outputStream) throws IOException {
		byte[] resultBytes = new byte[bytes.length + outputHeaderLength];
		byte[] headBytes = createHeader(bytes);
		log.debug("headBytes: " + new String(headBytes));
		/*StringBuilder stringBuilder = new StringBuilder();
		for (int i = 0; i < outputHeaderLength - (bytes.length+"").length(); i++) {
			stringBuilder.append("0");
		}
		stringBuilder.append(bytes.length+"")*/;
		System.arraycopy(headBytes, 0, resultBytes, 0, outputHeaderLength);
		System.arraycopy(bytes, 0, resultBytes, outputHeaderLength, bytes.length);
		log.debug("response: ");
		log.debug(new String(resultBytes));
		outputStream.write(resultBytes);
	}
	/** 形成长度位报文头 */
	public byte[] createHeader(byte[] bytes) {
		StringBuilder stringBuilder = new StringBuilder();
		for (int i = 0; i < outputHeaderLength - (bytes.length+"").length(); i++) {
			stringBuilder.append("0");
		}
		stringBuilder.append(bytes.length+"");
		return stringBuilder.toString().getBytes();
	}

	public void setInputHeaderLength(int inputHeaderLength) {
		this.inputHeaderLength = inputHeaderLength;
	}

	public void setOutputHeaderLength(int outputHeaderLength) {
		this.outputHeaderLength = outputHeaderLength;
	}

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}
}
