package com.ruoyi.framework.config;

import com.ruoyi.common.mqtt.MqttSSLUtils;
import com.ruoyi.common.mqtt.OnMessageCallback;
import com.ruoyi.common.mqtt.YuMqttClient;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttMessageListener;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * @author Duke_yzl
 * @date 20230605.01
 * @describe：MQTT订阅  回调地址涉及到redis使用DependsOn注解优先加载redis工具类
 */
@Slf4j
@Configuration
@ConfigurationProperties("mqtt")
@Data
//@DependsOn("redisUtils")
public class MqttConfig {

    private String host;
    private String clientId;
    private String[] topic;
    private Integer qos;
    private String username;
    private String password;
    private Integer timeout;
    private Integer keepalive;
    private Boolean isSsl;


    @Resource
    IMqttMessageListener mqttMessageListener;

    @Bean
    public YuMqttClient mqttClient(){
        try {
            YuMqttClient client = new YuMqttClient(host, clientId, new MemoryPersistence(),mqttMessageListener);
            // MQTT 连接选项
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setUserName(username);
            connOpts.setPassword(password.toCharArray());
            // 保留会话
            connOpts.setCleanSession(false);
            connOpts.setAutomaticReconnect(true);
            // 设置CA证书
            if (isSsl){
                try {
                    String caCrtFile = "mqtt/emqxsl-ca.crt";
                    connOpts.setSocketFactory(MqttSSLUtils.getSingleSocketFactory(caCrtFile));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
            // 设置回调
            client.setCallback(new OnMessageCallback(client));

            // 建立连接
            log.info("Connecting to broker: " + host);
            //设置链接完成后的监听
            client.connect(connOpts);

            log.info("连接成功");
            int[] qoss = new int[topic.length];
            //给所有的数组赋值
            Arrays.fill(qoss, qos);
            // 订阅
            client.subscribe(topic,qoss);
            return client;
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
    }

}

