const { uuid } = require("@supercharge/strings/dist")
const config = require('../../config.json')
const boskrypt = require('../../boskrypt')
const Connector = require("./Connector")
const md5 = require('md5')
const MQTT = require('async-mqtt')

class POCSAGConnector extends Connector {
    constructor (amqpConnMngr) {
        super(amqpConnMngr)
        this.name = "pocsag"
        this.duplexCapable = false
        this.supportBOSkrypt = true

        this.client = MQTT.connect(config.connectors.pocsag.mqttserver, {
            username: config.connectors.pocsag.username,
            password: config.connectors.pocsag.password,
            connectTimeout: 10,
        })
        this.client.on('error', (e) => console.error(e))
        this.client.on('connect', this.onMQTTConnect.bind(this))
        this.client.on('message', this.onMQTTMessage.bind(this))
        console.log("pocsag connector initalized",
            config.connectors.pocsag.mqttserver,
            config.connectors.pocsag.username,
            config.connectors.pocsag.password
        )
    }
    async onMQTTConnect() {
        // await this.client.subscribe(`v3/${ config.connectors.pocsag.username }/devices/#`)
        // await this.client.subscribe(`${ config.connectors.pocsag.username }/devices/#`)
        console.log('[pocsag] subscribed')
    }
    async onMQTTMessage(topic, message) {
        console.log(topic, message)
    }
    async transmitMessage(msg, params) {
        const UUID = this.name+':'+md5(JSON.stringify([this.name,...params]))
        if (params.length < 1) return false
        const RIC = params[0]
        const lastChar = RIC[RIC.length - 1].charCodeAt(0) - 65
        const addressPart = lastChar >= 0 && lastChar <= 3 ? RIC.substring(0, RIC.length - 1) : RIC
        const functionBits = lastChar >= 0 && lastChar <= 3 ? lastChar : 0

        let payloadBuffer = Buffer.from(msg.payload)

        const $device = msg.routingParams.device
        // todo centralize this in a encryptionManager to then make it easier to integrate with eCitryruf
        const boskryptSupport = require("../DeviceRegistry").Devices[ $device ].supportBOSkrypt || false
        if (boskryptSupport && !!config.boskrypt && config.boskrypt.enabled) {
            //payloadBuffer
            const keyTable = config.boskrypt.keys
            if (!!keyTable[ RIC ]) {
                payloadBuffer = Buffer.from(boskrypt.encrypt(payloadBuffer, keyTable[ RIC ], 0))
            }
        }

        let payload = {
            ric: parseInt(addressPart, 10),
            fun: functionBits,
            msg: payloadBuffer.toString("ascii")
        }
        console.log (config.connectors.pocsag, payloadBuffer.toString("ascii"), payload)
        await this.client.publish(config.connectors.pocsag.topic, JSON.stringify(payload))
        .then(() => {
            this.connectorRegistry.reportState(msg, UUID, 'routed')
            return true
        }).catch((err) => {
            this.connectorRegistry.reportFail(msg, UUID)
            return false
        })
    }
  }
  module.exports = POCSAGConnector