const Connector = require("./Connector")
const config = require('../../config.json')
const md5 = require('md5')
const axios = require('axios')
const WebSocket = require('ws')

class TetraControlConnector extends Connector {
  constructor (amqpConnMngr) {
    super(amqpConnMngr)
    this.name = "tetracontrol"
    this.duplexCapable = false
  }
  async transmitMessage(msg, params) {
      const UUID = this.name+':'+md5(JSON.stringify([this.name,...params]))
      if (params.length < 1) return false
      const target = params[0]
      //if (target.split('#').length !== 2) throw 'No valid DAPNET Parameter <transmitterGroup#callSign>'
      //const transmitterGroup = target.split('#')[ 0 ], callsign = target.split('#')[ 1 ]
      /*const dapnetRequest = {
        text: msg.payload,
        callSignNames: [ callsign ],
        transmitterGroupNames: [ transmitterGroup ]
      }*/

      const token = Buffer.from(`${ config.connectors.tetracontrol.username }:${ config.connectors.tetracontrol.password }`, 'utf8').toString('base64');
      const headers = {
        Authorization: `Basic ${token}`,
      }
      const ws = new WebSocket(`ws://${ config.connectors.tetracontrol.endpoint }/live.json?MaxAlter=3600`, { headers });
      return new Promise((res, rej) => {
	ws.on('open', function open() {
            console.log('WebSocket connected');
            const jsonData = {
                text: msg.payload,
                destSSI: target + '',
                ProtocolID: 9,
                radioID: 1,
                type: "sds"
            }
            ws.send(JSON.stringify(jsonData))
	    ws.close()
        })
        ws.on('close',res)
        ws.on('error',rej)

      })
      .then(() => {
        this.connectorRegistry.reportState(msg, UUID, 'routed')
        return true
      })
      .catch((err) => {
        console.error(err	)
        this.connectorRegistry.reportFail(msg, UUID)
        return false
      })
  }
}
module.exports = TetraControlConnector
