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;

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 ACUCommandResponsePool responsePool;
	
	private ACUClientUtil() {
		responsePool = new ACUCommandResponsePool();
		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连接未建立");
		}
	}
	
}
