package com.ruoyi.common.utils;

import com.ruoyi.common.mqtt.YuMqttClient;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @author Duke_yzl
 * @date 20230605.01
 * @describe：
 */
@Component
@Slf4j
public class MqttUtil {

    @Resource
    private YuMqttClient clients;
    private static YuMqttClient client;

    @PostConstruct
    public void init() {
        client = clients;
    }

    /**
     * 订阅主题
     * @param topic
     * @param qos
     */
    public static void subscribe(String topic, int qos) {
        try {
            client.subscribe(topic, qos);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
    /**
     * 订阅主题
     * @param topic
     */
    public static void subscribe(String topic) {
        try {
            client.subscribe(topic);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
    /**
     * 发布消息
     *
     * @param qos         连接方式 0,1,2 默认0
     *
     * @param retained    是否保留最新的消息
     * @param topic       订阅主题
     * @param pushMessage 消息体
     */
    public static void publish(int qos, boolean retained, String topic, String pushMessage) {
        MqttMessage message = new MqttMessage();
        message.setQos(qos);
        message.setRetained(retained);
        message.setPayload(pushMessage.getBytes());
        MqttTopic mqttTopic = client.getTopic(topic);
        if (null == mqttTopic) {
            log.error("topic not exist");
        }
        MqttDeliveryToken token;
        try {
            token = mqttTopic.publish(message);
            token.waitForCompletion();
        } catch (MqttPersistenceException e) {
            e.printStackTrace();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发布消息 并保留最后一次消息
     * @param topic 主题
     * @param pushMessage 消息内容
     */
    public static void publishReserve( String topic, String pushMessage) {
        publish(2,true,topic,pushMessage);

    }
    /**
     * 发布消息
     * @param topic 主题
     * @param pushMessage 消息内容
     */
    public static void publish( String topic, String pushMessage) {
        publish(2,false,topic,pushMessage);

    }
}
