exports.ClientPool = ClientPool;

var util = require("util");
var events = require("events");
var tool = require("../tool");
var tcp_client = require("./tcp_client");


function ClientPool(){
	events.EventEmitter.call(this);
	this.client_map_ = {};
}

util.inherits(ClientPool, events.EventEmitter);

ClientPool.prototype.SendToAddr = function (msg,addr){

	var obj = tool.ParseAddr(addr);
	if(!obj){
		console.log(obj)
		return false;
	}
	var cli = this.client_map_[addr];
	if(!cli){
		var self = this;
		cli = new tcp_client.TcpClient();
		cli.Connect(obj.ip,obj.port);
		cli.on("openfail",function(){
			self._OnCLose(addr);
		})
		cli.on("message",function(msg){
			self._OnMessage(addr,msg);
		})
		cli.on("close",function(){
			self._OnCLose(addr);
		})
		this.client_map_[addr] = cli;
	}
	return cli.Send(msg);
}
ClientPool.prototype._OnCLose = function (addr){
	delete this.client_map_[addr];
	this.emit("close",addr);
}
ClientPool.prototype._OnMessage = function (addr,msg){
	this.emit("message",addr,msg);
}