package cn.iododer.yudao.module.mqtt.config;

import cn.iododer.yudao.module.mqtt.service.MqttService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttAsyncClient;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.context.annotation.Configuration;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * MQTT回调
 */
@Slf4j
@Configuration
public class MqttCallBack implements MqttCallback {


    private static final ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);

    /**
     * 与服务器断开的回调
     */
    @Override
    public void connectionLost(Throwable throwable) {
        log.info("[MQTT]断开了与服务端的连接。考虑是否服务端掉线 or 回调参数解析报错 or 无默认sub");
        // 执行自动重连
        MqttFactory.reconnect();
    }

    /**
     * 消息到达的回调
     *
     * @param topic 话题
     * @param mqttMessage 消息内容
     */
    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        fixedThreadPool.execute(() -> {
            String msg = new String(mqttMessage.getPayload(), StandardCharsets.UTF_8);
//        log.info("[MQTT]接收当前消息为 :{}", msg);

            try {
                MqttService mqttService = MqttFactory.getMqttFactory(topic);
                mqttService.analysisMessage(msg);
            } catch (Exception e) {
                log.info("消费失败的消息主题 :{},消息内容 :{}", topic, msg);
                log.info("消费消息异常 :{}", e);
            }
        });

    }

    /**
     * 消息发布成功的回调
     *
     * @param token token
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        IMqttAsyncClient client = token.getClient();
//        log.info("[MQTT]{}：消息发布成功！", client.getClientId());
    }

}