import assign from 'lodash.assign'
import createDebug from 'debug'
import WebSocket from 'ws'

const debug = createDebug('xo:wsProxy')

const defaults = {
  // Automatically close the client connection when the remote close.
  autoClose: true
}

// Proxy a WebSocket `client` to a remote server which has `url` as
// address.
export default function wsProxy (client, url, opts) {
  opts = assign({}, defaults, opts)
  const autoClose = !!opts.autoClose
  delete opts.autoClose

  function onClientSendError (error) {
    debug('client send error', error)
  }
  function onRemoteSendError (error) {
    debug('remote send error', error)
  }

  const remote = new WebSocket(url, opts).once('open', function () {
    debug('connected to %s', url)
  }).once('close', function () {
    debug('remote closed')

    if (autoClose) {
      client.close()
    }
  }).once('error', function (error) {
    debug('remote error: %s', error)
  }).on('message', function (message) {
    client.send(message, onClientSendError)
  })

  client.once('close', function () {
    debug('client closed')
    remote.close()
  }).on('message', function (message) {
    remote.send(message, onRemoteSendError)
  })
}

@@ -490,29 +490,41 @@
 onClientSend
-E
+ (e
 rror
+) %7B%0A    if
  (error) %7B%0A 
@@ -514,32 +514,34 @@
    if (error) %7B%0A
+  
     debug('clien
@@ -558,24 +558,30 @@
 or', error)%0A
+    %7D%0A
   %7D%0A  functi
@@ -595,21 +595,33 @@
 moteSend
-E
+ (e
 rror
+) %7B%0A    if
  (error)
@@ -615,32 +615,34 @@
    if (error) %7B%0A
+  
     debug('remot
@@ -663,16 +663,22 @@
  error)%0A
+    %7D%0A
   %7D%0A%0A  c
@@ -1034,29 +1034,24 @@
 onClientSend
-Error
 )%0A  %7D)%0A%0A  cl
@@ -1210,13 +1210,8 @@
 Send
-Error
 )%0A  

Fix send error messages in wsProxy.