import WebSocket = require('ws')
import { DataBridgeConnectionManager } from './data-bridge-manager'
import { pubsub } from '@things-factory/shell'

const debug = require('debug')('aidoop:data-bridge')

class DataBridge {
  private wssExt: WebSocket.Server
  private portExt: number

  constructor(portExt: number) {
    this.portExt = portExt
  }

  start() {
    if (!this.wssExt) {
      this.wssExt = new WebSocket.Server({ port: this.portExt })
    }
    this.wssExt.on('connection', ws => {
      ws.on('message', message => {
        this.sendToClient(message.toString())
      })
      ws.on('error', error => {
        debug('recv. error from ext. module')
      })
    })
  }

  sendToExt(message: string) {
    this.wssExt.clients.forEach(client => {
      if (client.readyState === WebSocket.OPEN) {
        try {
          client.send(message)
        } catch (e) {
          debug('sendToExt')
          debug(e.name + ':' + e.message)
        }
      }
    })
  }

  sendCmdToExt(cmd: string, name: string) {
    const message = {
      type: 'cmd',
      name: name,
      body: cmd
    }

    this.sendToExt(JSON.stringify(message))
  }

  sendToClient(message: string) {
    try {
      var { name, body } = JSON.parse(message as any) as any
      pubsub.publish('data', {
        data: {
          domain: { subdomain: 'system' },
          tag: name,
          data: body
        }
      })
    } catch (e) {
      debug(`sendToClient errior: ${e.name} : ${e.message}`)
    }
  }
}

export var dataBridge = new DataBridge(34000)
