package com.ruoyi.common.mqtt;

import org.eclipse.paho.client.mqttv3.IMqttMessageListener;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttClientPersistence;
import org.eclipse.paho.client.mqttv3.MqttException;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Duke_yzl
 * @date 20230606.01
 * @describe：
 */
public class YuMqttClient extends MqttClient {

    //使用 hashMap防止出现重复的订阅
    private Map<String,Integer> topicMap = new HashMap<>();
    //自定义消息监听处理器
    private IMqttMessageListener mqttMessageListener;


    public YuMqttClient(String serverURI, String clientId, MqttClientPersistence persistence,IMqttMessageListener mqttMessageListener) throws MqttException {
        super(serverURI, clientId, persistence);
        this.mqttMessageListener = mqttMessageListener;
    }



    @Override
    public void subscribe(String topic, int qos) throws MqttException {
        super.subscribe(topic, qos, mqttMessageListener);
        topicMap.put(topic,qos);
    }
    @Override
    public void subscribe(String topic) throws MqttException {
        super.subscribe(topic, mqttMessageListener);
        topicMap.put(topic,1);
    }
    @Override
    public void subscribe(String[] topic, int[] qos) throws MqttException {
        super.subscribe(topic, qos, create(topic.length));
        for (int i = 0; i < topic.length; i++) {
            topicMap.put(topic[i],qos[i]);
        }
    }

    /**
     * 重新添加订阅
     * @throws MqttException
     */
    public void resubscribe() throws MqttException {
        super.subscribe(getTopicList(), getQosList(), create(getTopicList().length));
    }



    public String[] getTopicList() {
        return topicMap.keySet().stream().map(String::valueOf).toArray(String[]::new);
    }

    public int[] getQosList() {
        return topicMap.values().stream().mapToInt(Integer::valueOf).toArray();
    }

    private IMqttMessageListener[] create(int size){
        IMqttMessageListener[] listenerArray = new IMqttMessageListener[size];
        Arrays.fill(listenerArray, mqttMessageListener);
        return listenerArray;
    }
}