package com.szpg.plc.server;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;

import com.szpg.plc.util.ByteUtil;

import io.netty.buffer.Unpooled;
import z.json.JSONObject;

public class ACUClientUtil {
	
	private final Logger logger = Logger.getLogger(this.getClass().getName());
	public static final Logger recv = Logger.getLogger("recv");
	public static final Logger send = Logger.getLogger("send");
	
	private static ACUClientUtil util = null;
	
	private Map<String, ACUClient> clients;
	
	public FINSCommandPool pool;
	
	private ACUClientUtil() {
		pool = new FINSCommandPool();
		clients = new ConcurrentHashMap<String, ACUClient>();
	}
	
	public static ACUClientUtil getInstance() {
		if (null == util)
			util = new ACUClientUtil();
		
		return util;
	}
	
	public Map<String, ACUClient> getClients() {
		return clients;
	}

	public void setClients(Map<String, ACUClient> clients) {
		this.clients = clients;
	}
	
	/**
	 * 将client添加到map中
	 * @param client
	 */
	public void addClient(ACUClient client) {
		clients.put(client.getKey(), client);
		logger.debug("添加到clients中" + client + "[++" + clients.size() + "]");
	}
	
	/**
	 * 将client从map中移除
	 * @param client
	 */
	public void removeClient(ACUClient client) {
		if (clients.containsKey(client.getKey())) {
			clients.remove(client.getKey());
			logger.debug("从clients中移除" + client + "[--" + clients.size() + "]");
		}
	}
	
	/**
	 * 从map中查找client
	 * @param key
	 * @return
	 */
	public ACUClient getClient(String key) {
		if (clients.containsKey(key)) 
			return clients.get(key);
		else 
			return null;
	}
	

	/**
	 * 通过TCP连接向PLC端发送命令
	 * 
	 * @param client
	 * @param content
	 */
	public void sendACUCommand(ACUClient client, byte[] content) {
		// 判断channel并发送消息
		if (null != client.getChannel() && client.getChannel().isActive() == true) {
			// 通过socket发送消息并记录日志
			ACUClientUtil.send.info(ByteUtil.binToHexString(content));
			
			client.getChannel().writeAndFlush(Unpooled.copiedBuffer(content));
		} else {
			logger.debug("与" + client + "的TCP连接未建立");
		}
	}
	
	/**
	 * 将响应发回WEB端，并从响应消息池中将其删除
	 * 
	 * @param sessionId
	 * @param rtu
	 * @param type
	 * @return
	 */
	public String getResponse(String sessionId, String rtu, String type) {
		String key = sessionId + "-" + rtu + "-" + type;
		if (pool.getMessageToResponse().containsKey(key)) {
			JSONObject item = pool.getMessageToResponse().get(key);
			pool.getMessageToResponse().remove(key);
			return item.toString();
		} else {
			return null;
		}
	}
}
