var util = require("util");
var events = require("events");
var  adcloud = require("node_adcloud");
var net = require("net");
exports.version = adcloud.client_version;
exports.Create = function(appid,proxyaddr){
	return new AdcloudClient(appid,proxyaddr);
}
function AdcloudClient(appid,proxyaddr){
	this.appid_ = appid;
	this.gate_client_ = new adcloud.GateClient(appid);
	this.proxy_client_ = new adcloud.ProxyClient(proxyaddr);
	var self =this;
	this.gate_client_.on("open",function(){
		self.emit("open");
	})
	this.gate_client_.on("message",function(buf){
		self.emit("message",buf);
	})
	this.gate_client_.on("close",function(err){
		self.emit("close",err);
	})
}

util.inherits(AdcloudClient, events.EventEmitter);
AdcloudClient.prototype.Connect = function(param){
	var self = this;
	this.proxy_client_.GetGate(this.appid_,function(err,addr){
		if(err != null){
			self.emit("close","get.free.gate.fail.err=<" + err + ">");
		}else{
			self._ConnectGate(addr.ip,addr.port,param);
		}
	})
}
AdcloudClient.prototype._ConnectGate = function(ip,port,param){
	this.gate_client_.Connect(ip,port,param);
}
AdcloudClient.prototype.Send = function(data){
	return this.gate_client_.Send(data);
}
AdcloudClient.prototype.Close = function(){
	this.gate_client_.CLose();
}