package com.evobms.project.bms.controller;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnProperty(name = "mqtt.enabled", havingValue = "true")
public class GBT32960MqttReceiver {
    @Value("${mqtt.host}")
    private String broker;
    @Value("${mqtt.clientId}")
    private String clientId;
    @Value("${mqtt.username:}")
    private String username;
    @Value("${mqtt.password:}")
    private String password;
    @Value("${mqtt.connectionTimeout:30}")
    private int connectionTimeout;
    @Value("${mqtt.keepAliveInterval:60}")
    private int keepAliveInterval;
    @Value("${mqtt.automaticReconnect:true}")
    private boolean automaticReconnect;
    @Value("${mqtt.cleanSession:true}")
    private boolean cleanSession;
    @Value("${mqtt.subscribeTopic:/bbox/+/#}")
    private String subscribeTopic;

    @Bean
    public void initMQtt() {
        try {
            MqttClient client = new MqttClient(broker, clientId, new MemoryPersistence());

            MqttConnectOptions options = new MqttConnectOptions();
            options.setCleanSession(cleanSession);
            options.setAutomaticReconnect(automaticReconnect);
            options.setConnectionTimeout(connectionTimeout);
            options.setKeepAliveInterval(keepAliveInterval);
            if (username != null && !username.isEmpty()) {
                options.setUserName(username);
            }
            if (password != null && !password.isEmpty()) {
                options.setPassword(password.toCharArray());
            }

            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                }

                @Override
                public void messageArrived(String topic, MqttMessage message) {
                    byte[] payload = message.getPayload();
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                }
            });

            client.connect(options);
            client.subscribe(subscribeTopic);
        } catch (Exception e) {
        }
    }
}
