
exports.GateClient = GateClient;
var translate = require("./translate");
var cli_msg = require("./client_message");
var msg_tag = require("./coder").TAG;

var util = require("util");
var events = require("events");
const STATE_INITED = 0;
const STATE_REGISTING = 1;
const STATE_REGISTED = 2;
const STATE_CLOSED = 3;

var ver = require("./version");

function GateClient(appid){
	events.EventEmitter.call(this);
	this.appid_ = appid;
	this.tcp_client_ = new translate.TcpClient();
	this.buf_list_ = [];
	this.state_ = STATE_INITED;
	this.tcp_client_.on("openfail",this._OnOpenFail.bind(this));
	this.tcp_client_.on("open",this._OnOpen.bind(this));
	this.tcp_client_.on("message",this._OnMessage.bind(this));
	this.tcp_client_.on("close",this._OnClose.bind(this));
	this.param_ = null;
}
util.inherits(GateClient, events.EventEmitter);
GateClient.prototype.Connect = function(ip,port,param){
	console.log(ip,port);
	if(this.state_ == STATE_INITED){
		this.state_ = STATE_REGISTING;
		if(param){
			if( Buffer.isBuffer(param) ){
				this.param_ = param;
			}else{
				if(typeof param != "string"){
					param = JSON.stringify(param);
				}
				this.param_ = new Buffer(Buffer.byteLength(param));
				this.param_.write(param);
			} 
		}
		
		return this.tcp_client_.Connect(ip,port);
	}
	
}
GateClient.prototype._OnOpenFail = function(err){
	this.emit("close",err);
}
GateClient.prototype._keepAlive = function(){
	var msg = new cli_msg.MClientKeepAlive();
	if(this.tcp_client_)this.tcp_client_.Send(msg);
}
GateClient.prototype._OnOpen = function(){
	var msg = new cli_msg.MClientReg(this.appid_,"nodejs_" + ver.CLIENT_VERSION,this.param_);
	this.tcp_client_.Send(msg);
}
GateClient.prototype._OnMessage = function(msg){
	var tag = msg.GetTag();
	if(tag == msg_tag.ADCLOUD_MESSAGE_TAG_CLIENT_REGIST_BACK){
		if(msg.code == 0){
			this.state_ = STATE_REGISTED;
			this.emit("open");
			this.timer_ = setInterval(this._keepAlive.bind(this),5000);
		}else {
			this.tcp_client_.Close();
			this.state_ = STATE_CLOSED;
			this.emit("close","regist.fail.code="+msg.code);
		}
		
	}else if(tag ==  msg_tag.ADCLOUD_MESSAGE_TAG_CLIENT_MESSAGE){
		this.emit("message",msg.buf_);
	}else if(tag ==  msg_tag.ADCLOUD_MESSAGE_TAG_CLIENT_KEEPALIVE){
		
	}else{
		console.log("unknow.tag.",tag);
	}
}
GateClient.prototype._OnClose = function(err){
	clearInterval(this.timer_);
	this.state_ = STATE_CLOSED;
	this.emit("close",err);
}
GateClient.prototype.Send = function(data){
	if(this.state_ != STATE_REGISTED){
		return false;
	}
	var buf;
	if( Buffer.isBuffer(data) ){
		buf = data;
	}else{
		if(typeof data != "string"){
			data = JSON.stringify(data);
		}
		buf = new Buffer(Buffer.byteLength(data));
		buf.write(data);
	} 
	var msg = new cli_msg.MClientMessage(buf);
	this.tcp_client_.Send(msg);
	return true;
}
GateClient.prototype.Close = function(){
	this.removeAllListeners();
	this.tcp_client_.Close();
}