
var translate = require("../translate");
var rpc_client = require("./rpc_client");

exports.AutoRpcClient = AutoRpcClient;


function AutoRpcClient(ip,port){
	this.ip_  = ip;
	this.port_ = port;
	this.tcp_client_ = null;
	this.rpc_client_ = new rpc_client.RpcClient(this._Send.bind(this));
}


AutoRpcClient.prototype._Send = function(msg){
	if(!this.tcp_client_){
		this._Open();
	}
	return  this.tcp_client_.Send(msg);

}
AutoRpcClient.prototype._Open = function(){
	var self = this;
	this.tcp_client_ = new translate.TcpClient();
	this.tcp_client_.Connect(this.ip_,this.port_);
	this.tcp_client_.on("openfail",function(){
		self._OnCLose();
	})
	this.tcp_client_.on("message",function(msg){
		self._OnMessage(msg);
	})
	this.tcp_client_.on("close",function(){
		self._OnCLose();
	})
}

AutoRpcClient.prototype._OnCLose = function (){
	this.tcp_client_.removeAllListeners();
	this.tcp_client_ = null;
	this.rpc_client_.OnClose();
}
AutoRpcClient.prototype._OnMessage = function (msg){
	this.rpc_client_.OnMsg(msg);
}

AutoRpcClient.prototype.Call = function(){
	this.rpc_client_.Call.apply(this.rpc_client_,arguments);
}
AutoRpcClient.prototype.Destroy = function(){
	if(this.tcp_client_){
		this.tcp_client_.Close();
		this.tcp_client_.removeAllListeners();
		this.tcp_client_ = null;
		this.rpc_client_.OnClose();
	}
	this.rpc_client_.Destroy();
}