package com.fuyuanshen.global.mqtt.config;

import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;


@Configuration
public class MqttConfiguration {

    @Autowired
    private MqttPropertiesConfig mqttPropertiesConfig;


    /**
     * 创建连接工厂
     **/
    @Bean
    public MqttPahoClientFactory mqttPahoClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(true); // 设置新会话

        // 修复用户名为null时的空指针异常
        String username = mqttPropertiesConfig.getUsername();
        if (username != null) {
            options.setUserName(username);
        }

        // 修复密码为null时的空指针异常
        String password = mqttPropertiesConfig.getPassword();
        if (password != null) {
            options.setPassword(password.toCharArray());
        }

        // 修复URL为null时的空指针异常
        String url = mqttPropertiesConfig.getUrl();
        if (url != null) {
            options.setServerURIs(new String[]{url});
        }

        options.setAutomaticReconnect(true); // 启用自动重连
        options.setConnectionTimeout(10); // 设置连接超时时间
        options.setKeepAliveInterval(60); // 设置心跳间隔
        factory.setConnectionOptions(options);
        return factory;
    }

}