"use strict";var Emitter=require("events").EventEmitter,util=require("util"),streams=require("../streams"),Headers=require("./headers"),Reader=require("./stream_reader"),Base=function(e,t,n){Emitter.call(this),Base.validateOptions(n||{},["maxLength","masking","requireMasking","protocols"]),this._request=e,this._reader=new Reader,this._options=n||{},this._maxLength=this._options.maxLength||this.MAX_LENGTH,this._headers=new Headers,this.__queue=[],this.readyState=0,this.url=t,this.io=new streams.IO(this),this.messages=new streams.Messages(this),this._bindEventListeners()};util.inherits(Base,Emitter),Base.validateOptions=function(e,t){for(var n in e)if(t.indexOf(n)<0)throw new Error("Unrecognized option: "+n)};var instance={MAX_LENGTH:67108863,STATES:["connecting","open","closing","closed"],_bindEventListeners:function(){var e=this;this.messages.on("error",function(){}),this.on("message",function(t){var n=e.messages;n.readable&&n.emit("data",t.data)}),this.on("error",function(t){var n=e.messages;n.readable&&n.emit("error",t)}),this.on("close",function(){var t=e.messages;t.readable&&(t.readable=t.writable=!1,t.emit("end"))})},getState:function(){return this.STATES[this.readyState]||null},addExtension:function(e){return!1},setHeader:function(e,t){return!(this.readyState>0)&&(this._headers.set(e,t),!0)},start:function(){if(0!==this.readyState)return!1;var e=this._handshakeResponse();return!!e&&(this._write(e),-1!==this._stage&&this._open(),!0)},text:function(e){return this.frame(e)},binary:function(e){return!1},ping:function(){return!1},pong:function(){return!1},close:function(e,t){return 1===this.readyState&&(this.readyState=3,this.emit("close",new Base.CloseEvent(null,null)),!0)},_open:function(){this.readyState=1,this.__queue.forEach(function(e){this.frame.apply(this,e)},this),this.__queue=[],this.emit("open",new Base.OpenEvent)},_queue:function(e){return this.__queue.push(e),!0},_write:function(e){var t=this.io;t.readable&&t.emit("data",e)}};for(var key in instance)Base.prototype[key]=instance[key];Base.ConnectEvent=function(){},Base.OpenEvent=function(){},Base.CloseEvent=function(e,t){this.code=e,this.reason=t},Base.MessageEvent=function(e){this.data=e},Base.PingEvent=function(e){this.data=e},Base.PongEvent=function(e){this.data=e},module.exports=Base;