import buffer from '../buffer';

function websocket({ url, bufferTime = 0 }, { feed }) {
  const buf = buffer(feed, bufferTime);
  let socket;

  return {
    start: () => {
      socket = new WebSocket(url);
      socket.binaryType = 'arraybuffer';

      socket.onmessage = event => {
        if (typeof event.data === 'string') {
          buf.pushEvent(JSON.parse(event.data));
        } else {
          buf.pushText(String.fromCharCode.apply(null, new Uint8Array(event.data)));
        }
      }
    },

    stop: () => {
      socket.close();
    }
  }
}

export { websocket };

@@ -140,41 +140,60 @@
 et;%0A
-%0A
   
-return %7B%0A    start: () =%3E %7B%0A  
+let reconnectDelay = 250;%0A%0A  function connect() %7B%0A
     
@@ -221,26 +221,24 @@
 t(url);%0A    
-  
 socket.binar
@@ -263,16 +263,77 @@
 er';%0A%0A  
+  socket.onopen = () =%3E %7B%0A      reconnectDelay = 250;%0A    %7D%0A%0A
     sock
@@ -364,18 +364,16 @@
 %7B%0A      
-  
 if (type
@@ -402,18 +402,16 @@
 ing') %7B%0A
-  
         
@@ -455,18 +455,16 @@
 ;%0A      
-  
 %7D else %7B
@@ -464,18 +464,16 @@
  else %7B%0A
-  
         
@@ -555,48 +555,377 @@
     
+  %7D%0A
     %7D%0A
+%0A
     
-  %7D%0A    %7D,%0A%0A    stop: () =%3E %7B%0A
+socket.onclose = event =%3E %7B%0A      if (!event.wasClean) %7B%0A        console.debug(%60reconnecting in $%7BreconnectDelay%7D...%60);%0A        setTimeout(connect, reconnectDelay);%0A        reconnectDelay = Math.min(reconnectDelay * 2, 5000);%0A      %7D%0A    %7D%0A  %7D%0A%0A  return %7B%0A    start: () =%3E %7B%0A      connect();%0A    %7D,%0A%0A    stop: () =%3E %7B%0A      if (socket !== undefined) %7B%0A  
     
@@ -938,24 +938,32 @@
 et.close();%0A
+      %7D%0A
     %7D%0A  %7D%0A%7D%0A

Implement reconnection with backoff for WebSocket driver