var WebSocket=require(".."),deflate=require("permessage-deflate"),fs=require("fs"),http=require("http"),https=require("https"),port=process.argv[2]||7e3,secure="tls"===process.argv[3],options={extensions:[deflate],ping:5},upgradeHandler=function(e,r,t){var n=new WebSocket(e,r,t,["irc","xmpp"],options);console.log("[open]",n.url,n.version,n.protocol,e.headers),n.pipe(n),n.onclose=function(e){console.log("[close]",e.code,e.reason),n=null}},requestHandler=function(e,r){if(!WebSocket.EventSource.isEventSource(e))return staticHandler(e,r);var t=new WebSocket.EventSource(e,r),n=parseInt(t.lastEventId,10)||0;console.log("[open]",t.url,t.lastEventId);var o=setInterval(function(){n+=1,t.send("Time: "+n),setTimeout(function(){t&&t.send("Update!!",{event:"update",id:n})},1e3)},2e3);fs.createReadStream(__dirname+"/haproxy.conf").pipe(t,{end:!1}),t.onclose=function(){clearInterval(o),console.log("[close]",t.url),t=null}},staticHandler=function(e,r){var t=e.url;fs.readFile(__dirname+t,function(e,t){var n=e?404:200;r.writeHead(n,{"Content-Type":"text/html"}),r.write(t||"Not found"),r.end()})},server=secure?https.createServer({key:fs.readFileSync(__dirname+"/../spec/server.key"),cert:fs.readFileSync(__dirname+"/../spec/server.crt")}):http.createServer();server.on("request",requestHandler),server.on("upgrade",upgradeHandler),server.listen(port);