import mqtt from 'mqtt'

export default class MQTTService {
  constructor(brokerUrl = 'ws://127.0.0.1:8083/mqtt', clientId = null) {
    this.clientId = clientId || 'vue-client-' + Math.random().toString(16).substr(2, 8)
    this.client = mqtt.connect(brokerUrl, { clientId: this.clientId, protocolVersion: 5 })
    this.subscriptions = [] // array of {topic, callback}

    this.client.on('connect', () => console.log('Connected to MQTT broker'))
    this.client.on('message', (topic, payload) => {
      // iterate over subscriptions and check for matches
      this.subscriptions.forEach(({ topic: subTopic, callback }) => {
        if (mqttMatch(subTopic, topic)) {
          callback(payload.toString(), topic)
        }
      })
    })
  }

  subscribe(topic, callback) {
    this.subscriptions.push({ topic, callback })
    this.client.subscribe(topic)
  }

  publish(topic, message, options = {}) {
    this.client.publish(topic, message, options)
  }
}

// helper function for MQTT wildcards
function mqttMatch(subTopic, topic) {
  // replace MQTT wildcards with RegExp
  const regex = '^' + subTopic.replace('+', '[^/]+').replace('#', '.+') + '$'
  return new RegExp(regex).test(topic)
}
