const mqtt = require('mqtt');
let settingsChangeSubscibers = [];

const mqttUrl = `mqtt://localhost:1883`;
const mqttClient  = mqtt.connect(mqttUrl, { 
  username: "scorit", 
  password: "WKepsYefCog2PMRZU6HdrZRLjjqfVK3CqWeVpWBbV9XbGUSGhyQpUDnu" 
});

let isMqttConnected = false;
const settingsTopic = "settings"//`car/${mashineId}/settings`;

mqttClient.on('connect', function () {
  console.log("mqtt is alive");
  isMqttConnected = true;
  mqttClient.subscribe(settingsTopic)
})

mqttClient.on('message', (topic, message) => {
  if(topic === settingsTopic) {
    settingsChangeSubscibers.forEach(callback => {
        if(typeof callback === "function")
            callback(JSON.parse(message.toString()));
    });
  }
});

const sendToQueue = (toppic, message) => {
  if(isMqttConnected) {
    mqttClient.publish(toppic, message)
  }
}

const subscribeToSettingsChange = (callback) => {
    settingsChangeSubscibers.push(callback);
}

module.exports = { sendToQueue, subscribeToSettingsChange }