package cn.net.cpzslibs.prot.handset;

import com.google.gson.Gson;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.Socket;

import cn.net.cpzslibs.prot.ProtBase;
import cn.net.cpzslibs.prot.SocketCreate;
import cn.net.cpzslibs.prot.handset.bean.Prot10049SendBean;
import cn.net.cpzslibs.prot.handset.bean.Prot10049UpPictrueBean;
import cn.net.cpzslibs.prot.utils.CRCUtils;
import cn.net.cpzslibs.prot.utils.StrUtils;

public class Prot10049UpPicture2 extends ProtBase {

	private final short iTaskCode10049 = 10049;

	private Gson gson;

	private Prot10049UpPictrueBean resBean;

	int index = 0;// 多少个包
	private String picName;
	
	private String extension = "jpg";
	
	private int failNum = 0;
	private int errcode = 0;
	
	

	public Prot10049UpPicture2(String picName,String extension) {
		gson = new Gson();
		this.picName = picName;
		this.extension = extension;

	}

	public Prot10049UpPictrueBean getResBean() {
		return resBean;
	}

	public void setResBean(Prot10049UpPictrueBean resBean) {
		this.resBean = resBean;
	}

	public void dealPicture(SocketCreate create, String strPath)
			throws IOException {
		recProt(create, strPath);

	}
	

	public int getFailNum() {
		return failNum;
	}

	public void setFailNum(int failNum) {
		this.failNum = failNum;
	}

	public int getErrcode() {
		return errcode;
	}

	public void setErrcode(int errcode) {
		this.errcode = errcode;
	}

	// static int t = 1;
	private void recProt(SocketCreate create, String strPath)
			throws IOException {
		Socket socket = create.getSocket();
		DataOutputStream dos = create.getDos();
		DataInputStream dis = create.getDis();
		if (create.getSocket().isConnected()) {
			if (!socket.isOutputShutdown()) {
				// 发送登录信息
				debugLog(iTaskCode10049, "开始发送图片信息" + strPath);
				if (!StrUtils.isEmpty(strPath)) {
					File file = new File(strPath);
					FileInputStream fis = new FileInputStream(file);
					int picSize = (int) file.length();
					int perPicSize = 60000;// 每次传送图片包的大小
					byte[] buf = new byte[perPicSize];
					int length = 0;
					int cLen = 0;
					debugLog(iTaskCode10049, "picSize:" + picSize);

					while ((length = fis.read(buf)) != -1) {
						cLen = cLen + length;
						debugLog(iTaskCode10049, "cLen:" + cLen + "   length:"
								+ length);
						index++;
						if (cLen >= picSize) {
							index = 0;
						}
						// System.err.println("---" + index);
						String jsonStr = gson.toJson(
								getImageUpBean(picName, picSize, extension,index))
								.toString();
						short bodySize = 0;
						bodySize = (short) (countBodySize(jsonStr) + length + 2);
						debugLog(iTaskCode10049, "   bodySize:" + bodySize
								+ "   jsonSize:" + jsonStr);
						sendHeader(dos, iTaskCode10049, bodySize);
						dos.writeShort((short) jsonStr.length());
						// dos.write(shortToByte((short) jsonStr.length()));
						dos.write(jsonStr.getBytes());
						dos.write(buf, 0, length);
						sendCheckCoded(dos, spliceByte(jsonStr, buf, length));
						// System.err.println("test:" + (t++) +"   crc"+
						// CRC16Util.CRC16(spliceByte(jsonStr, buf, length)));

						/*
						 * if (socket.isConnected()) { if
						 * (!socket.isInputShutdown()) { recJson(dis); } }
						 */

						if (socket.isConnected()) {
							if (!socket.isInputShutdown()) {
								recJson(dis);
							}
						}
					}
				} else {
					int picSize = 0;
					String jsonStr = gson.toJson(getImageUpBean(picName, 0,extension, 0))
							.toString();

					short bodySize = (short) (countBodySize(jsonStr) + 2);
					debugLog(iTaskCode10049, "   bodySize:" + bodySize);
					sendHeader(dos, iTaskCode10049, bodySize);
					dos.writeShort((short) jsonStr.length());
					dos.write(jsonStr.getBytes());
					// System.err.println("-picSize---" + jsonStr.length());
					short crc = CRCUtils.CRC16(spliceByte(jsonStr));
					dos.writeShort(crc);

				}

				// socket.shutdownOutput();
				/*
				 * if (socket.isConnected()) { if (!socket.isInputShutdown()) {
				 * recJson(dis); } }
				 */
			}

		}

	}

	private void recJson(DataInputStream dis) throws IOException {
		// TODO Auto-generated method stub
		debugLog(iTaskCode10049, "获取接收的数据");
		recHeader(dis);
		int jsonLength = getiRecBodySize() - 2;
		String jsonData = getUTF8(dis, jsonLength);
		debugLog(iTaskCode10049, jsonData);
		if (!StrUtils.isEmpty(jsonData)) {
			resBean = gson.fromJson(jsonData, Prot10049UpPictrueBean.class);
			failNum +=resBean.getResult();
			errcode =resBean.getErrcode();
			debugLog(iTaskCode10049+"多次累加异常码", "failNum"+failNum+"--errcode"+errcode);
		}
		
		recCheckCode(dis);
	}

	private byte[] spliceByte(String jsonStr) {
		try {

			byte[] b1 = shortToByte((short) jsonStr.length());
			byte[] b2 = jsonStr.getBytes("UTF-8");// [123, 34, 110, 97, 109,
													// 101, 34, 58, 34, 116,
													// 101, 115, 116, 69, 99,
													// 104, 111, 34, 44, 34,
													// 115, 105, 122, 101, 34,
													// 58, 48, 44, 34, 105, 110,
													// 100, 101, 120, 34, 58,
													// 48, 125]
			byte[] count = new byte[b1.length + b2.length];
			System.arraycopy(b1, 0, count, 0, b1.length);
			System.arraycopy(b2, 0, count, b1.length, b2.length);
			// [123, 34, 110, 97, 109, 101, 34, 58, 34, 116, 101, 115, 116, 69,
			// 99, 104, 111, 34, 44, 34, 115, 105, 122, 101, 34, 58, 48, 44, 34,
			// 105, 110, 100, 101, 120, 34, 58, 48, 125]
			// [38, 0, 123, 34, 110, 97, 109, 101, 34, 58, 34, 116, 101, 115,
			// 116, 69, 99, 104, 111, 34, 44, 34, 115, 105, 122, 101, 34, 58,
			// 48, 44, 34, 105, 110, 100, 101, 120, 34, 58, 48, 125]
			// System.err.println("  count:" + count.length);
			return count;
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

	private byte[] spliceByte(String jsonStr, byte[] buf, int length) {
		try {

			byte[] b1 = shortToByte((short) jsonStr.length());
			byte[] b2 = jsonStr.getBytes("UTF-8");
//			System.out.println(" jsonStr:  " + jsonStr);
			debugLog(iTaskCode10049, " jsonStr:  " + jsonStr);
			byte[] count = new byte[b1.length + b2.length + length];
			System.arraycopy(b1, 0, count, 0, b1.length);
			System.arraycopy(b2, 0, count, b1.length, b2.length);
			System.arraycopy(buf, 0, count, b1.length + b2.length, length);
			/*
			 * if (length == buf.length) { System.arraycopy(buf, 0, count,
			 * b1.length + b2.length, buf.length); } else {
			 * System.arraycopy(buf, 0, count, b1.length + b2.length, length);
			 * // for(int i=) }
			 */

			return count;
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

	/**
	 * 注释：short到字节数组的转换！
	 * 
	 * @param number
	 * @return
	 */
	private byte[] shortToByte(short number) {
		int temp = number;
		byte[] b = new byte[2];
		/*
		 * for (int i = 0; i < b.length; i++) { b[i] = new Integer(temp &
		 * 0xff).byteValue();// 将最低位保存在最低位 temp = temp >> 8; // 向右移8位 }
		 */

		for (int i = b.length - 1; i > 0; i--) {
			b[i] = new Integer(temp & 0xff).byteValue();// 将最低位保存在最低位
			temp = temp >> 8; // 向右移8位
		}

		return b;
	}

	private Prot10049SendBean getImageUpBean(String pictureName,
			int pictureSize, String extension,int index ) {
		Prot10049SendBean sendBean = new Prot10049SendBean(pictureName,
				pictureSize, extension,index);

		return sendBean;
	}

	private void sendProt(SocketCreate create, String strPath) {
		// TODO Auto-generated method stub

	}

}
