package com.saga.thread.up;

import java.util.ArrayList;
import java.util.List;

import org.zillion.util.log.LogUtil;

import com.persagy.communication.entity.Packet;
import com.persagy.communication.mina.tcp.client.TCPClientManager;
import com.persagy.communication.mina.udp.client.UDPClientManager;
import com.persagy.communication.util.IClientManager;
import com.saga.util.Constant;

/**
 * 数据转发
 *
 * @author 李井强
 */
public class TransferThread extends Thread {
	private IClientManager transferClient = null;

	public TransferThread() {
		try {
			// if
			// ("UDP".equalsIgnoreCase(Constant.transfer.PROTOCOL.toString())) {
			// if (Constant.transfer.compress) {
			// this.transferClient = new
			// UDPClientManager(Constant.transfer.IP.toString(),
			// Constant.transfer.Port,
			// Constant.transfer.ServerIP.toString(),
			// Constant.transfer.ServerPort, "utf-8", true,
			// Constant.transfer.Max_size);
			// } else {
			// this.transferClient = new
			// UDPClientManager(Constant.transfer.IP.toString(),
			// Constant.transfer.Port,
			// Constant.transfer.ServerIP.toString(),
			// Constant.transfer.ServerPort, "utf-8", false,
			// Constant.transfer.Max_size);
			// }
			// } else {
			// if (Constant.transfer.compress) {
			// if ("true".equalsIgnoreCase(Constant.transfer.Separate)) {
			// this.transferClient = new
			// TCPClientManager(Constant.transfer.ServerIP.toString(),
			// Constant.transfer.ServerPort, "utf-8", true,
			// Constant.transfer.Max_size,
			//// (byte) Constant.transfer.Separate_begin.charAt(0),
			//// (byte) Constant.transfer.Separate_end.charAt(0)
			// (byte) '(', (byte) ')'
			// );
			// } else {
			// this.transferClient = new
			// TCPClientManager(Constant.transfer.ServerIP.toString(),
			// Constant.transfer.ServerPort, "utf-8", true,
			// Constant.transfer.Max_size);
			// }
			// } else {
			// if ("true".equalsIgnoreCase(Constant.transfer.Separate)) {
			// this.transferClient = new
			// TCPClientManager(Constant.transfer.ServerIP.toString(),
			// Constant.transfer.ServerPort, "utf-8", false,
			// Constant.transfer.Max_size,
			//// (byte) Constant.transfer.Separate_begin.charAt(0),
			//// (byte) Constant.transfer.Separate_end.charAt(0)
			// (byte) '(', (byte) ')'
			// );
			// } else {
			// this.transferClient = new
			// TCPClientManager(Constant.transfer.ServerIP.toString(),
			// Constant.transfer.ServerPort, "utf-8", false,
			// Constant.transfer.Max_size);
			// }
			// }
			// }
			if ("UDP".equalsIgnoreCase(Constant.transfer.PROTOCOL.toString())) {
				this.transferClient = new UDPClientManager(Constant.transfer.IP.toString(), Constant.transfer.Port,
						Constant.transfer.ServerIP.toString(), Constant.transfer.ServerPort, "gbk", false,
						Constant.transfer.Max_size);
			} else {
				this.transferClient = new TCPClientManager(Constant.transfer.ServerIP.toString(),
						Constant.transfer.ServerPort, "gbk", false, Constant.transfer.Max_size, (byte) '(', (byte) ')');
			}

			this.transferClient.Start();
			LogUtil.info("TransferThread" + ": " + this.transferClient.Name() + " Created ...");
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.error("TransferThread.Exception: " + e.toString());
			LogUtil.info("TransferThread" + ": " + this.transferClient.Name() + " failed to excute, exit!");
			// System.exit(0);
		}
	}

	public void run() {
		while (true) {
			try {
				// 处理PopRece包
				Packet packageRece = this.transferClient.PopRece();
				if (packageRece != null) {
					this.handlePopRece(packageRece);
				}
				// 转发report包
				this.transferReport();
				Thread.sleep(1L);
			} catch (Exception e) {
				LogUtil.error("TransferThread.run.Exception: " + e.toString());
			}
		}
	}

	/**
	 * 转发数据报文
	 */
	private void transferReport() {
		List<String> reportList = new ArrayList<String>();
		synchronized (Constant.TransferReportList) {
			reportList.addAll(this.valaidTransferReport(Constant.TransferReportList));
			Constant.TransferReportList.clear();
		}

		for (String report : reportList) {
			try {
				this.transferClient.AppendToSend(new Packet(report));
				Thread.sleep(1L);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		Constant.transferSendCount += reportList.size();
	}

	/**
	 * 生成有效转发数据报文
	 */
	private List<String> valaidTransferReport(List<String> transferReportList) {
		List<String> result = new ArrayList<String>();
		for (String report : transferReportList) {
			try {
				String[] list = report.split(";");
				String buildingSign = list[0];
				String meterSign = list[5];
				int funcID = Integer.valueOf(list[7]);
				if (!isTransfer(buildingSign, meterSign, funcID)) {
					continue;
				}
				result.add(report);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 数据报文处理
	 */
	private void handlePopRece(Packet packageRece) {
		if (packageRece != null && packageRece.packetString != null && packageRece.packetString.length() > 0) {
			LogUtil.info(this.transferClient.Name() + " PopRece: " + packageRece.packetString);
			Constant.transferRecCount++;
		}
	}

	/**
	 * 是否需要转发
	 * 
	 * @param buildingSign
	 *            楼号
	 * @param meterSign
	 *            表号
	 * @param funcID
	 *            功能号
	 */
	private boolean isTransfer(String buildingSign, String meterSign, int funcID) {
		// TODO Auto-generated method stub
		if (isTransfer_building(buildingSign) && isTransfer_Point(buildingSign, meterSign, funcID)) {
			return true;
		}
		return false;
	}

	/**
	 * 是否需要转发
	 * 
	 * @param meterSign
	 * @param buildingSign
	 */
	private boolean isTransfer_Point(String buildingSign, String meterSign, int funcID) {
		// TODO Auto-generated method stub
		if (Constant.transfer_List == null || Constant.transfer_List.size() == 0) {
			return true;
		}
		if (Constant.transfer_List.containsKey(buildingSign + "-" + meterSign + "-" + funcID)
				|| Constant.transfer_List.containsKey(buildingSign + "-" + meterSign + "-" + "all")
				|| Constant.transfer_List.containsKey(buildingSign + "-" + "all" + "-" + "all")
				|| Constant.transfer_List.containsKey(buildingSign + "-" + "all" + "-" + funcID)) {
			return true;
		}
		return false;
	}

	/**
	 * 是否需要转发
	 */
	private boolean isTransfer_building(String buildingSign) {
		// TODO Auto-generated method stub
		if (!Constant.transfer_List.containsKey(buildingSign)) {
			return true;
		}
		return false;
	}

}