package be.naaturel.boardmateapi.configurations.configurations;

import be.naaturel.boardmateapi.common.helpers.Logger;
import be.naaturel.boardmateapi.configurations.properties.MqttProperies;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MqttConfig {

    private final MqttProperies properties;

    @Autowired
    public MqttConfig(MqttProperies properties){
        this.properties = properties;
    }

    @Bean("mqttPublisher")
    public MqttClient mqttPublisher() throws MqttException {
        MqttClient client = new MqttClient(properties.getBrokerUrl(), properties.getClientId());
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(properties.getUsername());
        options.setPassword(properties.getPassword().toCharArray());
        return client;
    }

    @Bean("mqttSubscriber")
    public MqttClient mqttSubscriber() throws MqttException {
        String subscriberId = properties.getClientId() + "-sub";
        MqttClient client = new MqttClient(properties.getBrokerUrl(), subscriberId);

        client.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable cause) {
                Logger.displayError("Connection lost: " + cause.getMessage());
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) {
                Logger.displayInfo("Received message on topic " + topic + ": " + message.toString());
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
                // Not needed for subscriber
            }
        });

        return client;
    }

}
