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


class pNetConnector extends Connector {
  constructor (amqpConnMngr) {
    super(amqpConnMngr)
    this.name = "pnet"
    this.duplexCapable = true
    this.managementSocket = false
  }
  async transmitMessage(msg, params) {
    console.log('pnet socket=',this.managementSocket)
    if (!this.managementSocket) {
      const { io } = require("socket.io-client")
      console.log('starting pnet socket')
      this.managementSocket = io("wss://<pnet url>")
      this.managementSocket.on('smartpager:ingress:event', (evt) => {
        console.log(evt)
        //this.connectorRegistry.reportState(msg, evt.UUID, evt.state)
        if (evt.delivered) this.connectorRegistry.reportDelivered({ id: evt.msgid }, `tetra:${ evt.device_id }`)
        //require('../MessageManager').markMessageRead(data.msgid)
        if (evt.response) require('../MessageManager').respondToMessage(evt.msgid, evt.response)
      })
      await this.managementSocket.connect()
    }
      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 pNet Parameter <transmitterGroup#callSign>'
      const contact = target.split('#')[ 0 ], options = target.split('#')[ 1 ]
      /*const extraParameters = {
        auth: {
          username: config.connectors.dapnet.username,
          password: config.connectors.dapnet.password
        }
      }*/
      this.managementSocket.emit('smartpager:ingress', {
        UUID,
        id: msg.id,
        text: msg.payload,
        contact,
        options,
      })
      return true
      /*return axios.post("https://pnet.cheetah.cat/", dapnetRequest, extraParameters)
      .then(() => {
        return true
      })
      .catch((err) => {
        console.error(err.response.data)
        this.connectorRegistry.reportFail(msg, UUID)
        return false
      })*/
  }
}
module.exports = pNetConnector