var util=require("util"),net=require("net"),tls=require("tls"),url=require("url"),driver=require("websocket-driver"),API=require("./api"),Event=require("./api/event"),DEFAULT_PORTS={"http:":80,"https:":443,"ws:":80,"wss:":443},SECURE_PROTOCOLS=["https:","wss:"],Client=function(r,e,t){t=t||{},this.url=r,this._driver=driver.client(this.url,{maxLength:t.maxLength,protocols:e}),["open","error"].forEach(function(r){this._driver.on(r,function(){c.headers=c._driver.headers,c.statusCode=c._driver.statusCode})},this);var i=t.proxy||{},o=url.parse(i.origin||this.url),s=o.port||DEFAULT_PORTS[o.protocol],n=SECURE_PROTOCOLS.indexOf(o.protocol)>=0,h=function(){c._onConnect()},a=t.net||{},p=t.tls||{},_=i.origin?i.tls||{}:p,c=this;a.host=_.host=o.hostname,a.port=_.port=s,p.ca=p.ca||t.ca,_.servername=_.servername||o.hostname,this._stream=n?tls.connect(_,h):net.connect(a,h),i.origin&&this._configureProxy(i,p),API.call(this,t)};util.inherits(Client,API),Client.prototype._onConnect=function(){(this._proxy||this._driver).start()},Client.prototype._configureProxy=function(r,e){var t,i=url.parse(this.url),o=SECURE_PROTOCOLS.indexOf(i.protocol)>=0,s=this;if(this._proxy=this._driver.proxy(r.origin),r.headers)for(t in r.headers)this._proxy.setHeader(t,r.headers[t]);this._proxy.pipe(this._stream,{end:!1}),this._stream.pipe(this._proxy),this._proxy.on("connect",function(){if(o){var r={socket:s._stream,servername:i.hostname};for(t in e)r[t]=e[t];s._stream=tls.connect(r),s._configureStream()}s._driver.io.pipe(s._stream),s._stream.pipe(s._driver.io),s._driver.start()}),this._proxy.on("error",function(r){s._driver.emit("error",r)})},module.exports=Client;