"use strict";var Stream=require("stream").Stream,url=require("url"),util=require("util"),Base=require("./base"),Headers=require("./headers"),HttpParser=require("../http_parser"),PORTS={"ws:":80,"wss:":443},Proxy=function(t,e,s){this._client=t,this._http=new HttpParser("response"),this._origin="object"==typeof t.url?t.url:url.parse(t.url),this._url="object"==typeof e?e:url.parse(e),this._options=s||{},this._state=0,this.readable=this.writable=!0,this._paused=!1,this._headers=new Headers,this._headers.set("Host",this._origin.host),this._headers.set("Connection","keep-alive"),this._headers.set("Proxy-Connection","keep-alive");var i=this._url.auth&&new Buffer(this._url.auth,"utf8").toString("base64");i&&this._headers.set("Proxy-Authorization","Basic "+i)};util.inherits(Proxy,Stream);var instance={setHeader:function(t,e){return 0===this._state&&(this._headers.set(t,e),!0)},start:function(){if(0!==this._state)return!1;this._state=1;var t=this._origin,e=t.port||PORTS[t.protocol],s=["CONNECT "+t.hostname+":"+e+" HTTP/1.1",this._headers.toString(),""];return this.emit("data",new Buffer(s.join("\r\n"),"utf8")),!0},pause:function(){this._paused=!0},resume:function(){this._paused=!1,this.emit("drain")},write:function(t){if(!this.writable)return!1;if(this._http.parse(t),!this._http.isComplete())return!this._paused;if(this.statusCode=this._http.statusCode,this.headers=this._http.headers,200===this.statusCode)this.emit("connect",new Base.ConnectEvent);else{var e="Can't establish a connection to the server at "+this._origin.href;this.emit("error",new Error(e))}return this.end(),!this._paused},end:function(t){this.writable&&(void 0!==t&&this.write(t),this.readable=this.writable=!1,this.emit("close"),this.emit("end"))},destroy:function(){this.end()}};for(var key in instance)Proxy.prototype[key]=instance[key];module.exports=Proxy;