exports.RpcClient = RpcClient;
var rpc_msg = require("./rpc_message");
var coder = require("../coder");
function RpcClient( sender ){
	this.sender_ = sender;
	this.seq_ = 1;
	this.seq_map = {};
	this.timer_ = setInterval(this._OnTimer.bind(this),1000);
}

RpcClient.prototype.Call = function(name,type,cb){
	var seq = this.seq_++;
	var msg = new rpc_msg.RpcRequest(name,seq,type);

	if( this.sender_(msg) ){
		this.seq_map[seq ] = {
			cb:cb,
			timeout:2,
		}
	}else{
		process.nextTick(function(){
			cb(null,"send fail");
		})
	}
}

RpcClient.prototype.OnMsg = function(msg){
	var item = this.seq_map[msg.seq_];
	if(item){
		delete this.seq_map[msg.seq_];
		var type = msg.GetType();
		if(type instanceof coder.TypeError){
			item.cb(null,type.error_);
		}else{
			item.cb(type,null);
		}
	}

}
RpcClient.prototype.OnClose = function(){
	var map = this.seq_map;
	this.seq_map = {};
	for(var i in  map){
		map[i].cb(null,"connect close");
	}
}

RpcClient.prototype._OnTimer = function(){
	for(var i in this.seq_map){
		var item = this.seq_map[i];
		if(item.timeout -- <= 0){
			item.cb(null,"timeout");
			delete this.seq_map[i];
		}
	}
}
RpcClient.prototype.Destroy = function(){
	clearInterval(this.timer_);
}