package com.ruoyi.common.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;

import java.util.Map;

/**
 * @author Duke_yzl
 * @date 20230606.01
 * @describe：
 */
@Slf4j
public class OnMessageCallback implements MqttCallbackExtended {

    private YuMqttClient client;

    /**
     * 自动注入mqtt配置
     *
     */

    /**
     * 用来记录指定的主题及其对应的监听器
     */
    private Map<String, IMqttMessageListener> topicFilterListeners;

    public OnMessageCallback(YuMqttClient yuMqttClient){
        this.client = yuMqttClient;
    }

    public void connectionLost(Throwable cause) {
        log.info("连接断开，正在重连....");
    }

    public void messageArrived(String topic, MqttMessage message) throws Exception {
        // subscribe后得到的消息会执行到这里面
        //通过监听器进行监听，不在此处输出
        System.out.println("接收消息主题:" + topic);
        System.out.println("接收消息Qos:" + message.getQos());
        System.out.println("接收消息内容:" + new String(message.getPayload()));
        client.subscribe(topic,message.getQos());
        client.publish(topic, message);

    }

    public void deliveryComplete(IMqttDeliveryToken token) {
        System.out.println("deliveryComplete---------" + token.isComplete());
    }

    @Override
    public void connectComplete(boolean reconnect, String serverURI) {
        if (reconnect){
            log.info("mqtt重连成功.");
            try {
                client.resubscribe();
            } catch (MqttException e) {
                throw new RuntimeException(e);
            }
        }
    }


}