export class DataBridgeClient {
  wsUrl
  socket
  callback
  appName

  constructor(port, appName, callback) {
    var protocol = location.protocol == 'http:' ? 'ws:' : 'wss:'
    this.wsUrl = `${protocol}//${window.location.hostname}:${port}`
    this.socket = null
    this.appName = appName
    this.callback = callback
  }

  connect() {
    this.socket = new WebSocket(this.wsUrl)

    this.socket.addEventListener('open', event => {
      console.log('websocket open', event)
    })

    this.socket.onmessage = message => {
      var { data } = message
      this.callback(data)
    }
  }

  disconnect() {
    //this.sendCmd('exit')
    // TODO: check if socket can last 'exit' command successfully before socket is closed.
    this.socket.close()
  }

  async sendCmd(command) {
    const message = {
      type: 'cmd',
      name: this.appName,
      body: command
    }

    this.socket.send(JSON.stringify(message))
  }
}
