package com.psdc.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.mapping.Environment;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * mqtt回调
 */
@Slf4j
@Component
public class MyMQTTCallback implements MqttCallback {


    private MyMQTTClient myMQTTClient;

    public MyMQTTCallback(MyMQTTClient myMQTTClient) {
        this.myMQTTClient = myMQTTClient;
    }

    /**
     * 丢失连接，可在这里做重连
     * 只会调用一次
     *
     * @param throwable
     */
    @Override
    public void connectionLost(Throwable throwable) {
        log.error("mqtt connectionLost 连接断开，5S之后尝试重连: {}", throwable.getMessage());
        long reconnectTimes = 1;
        while (true) {
            try {
                if (MyMQTTClient.getClient().isConnected()) {
                    //连接成功，重新订阅主题
                    log.warn("重新链接成功，重新订阅主题");
                    MqttClient client = MyMQTTClient.getClient();
                    client.subscribe("/psdc/devices/1672921261340/datas/report/#", 1);
                    log.warn("重新订阅成功");
                    return ;
                }
                log.warn("mqtt reconnect times = {} try again...", reconnectTimes++);
                MyMQTTClient.getClient().reconnect();
            } catch (MqttException e) {
                log.error("e", e);
            }
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e1) {
                log.error("e1",e1);
            }
        }
    }

    /**
     * @param topic
     * @param mqttMessage
     * @throws Exception
     * subscribe后得到的消息会执行到这里面
     */
    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        log.info("接收消息主题 : {}，接收消息内容 : {}", topic, new String(mqttMessage.getPayload()));

        try {

        } catch (Exception e){
            e.printStackTrace();
        }
        log.info("MQTT接受结束");
    }


    /**
     * publish后，配送完成后回调的方法
     *
     * @param iMqttDeliveryToken
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        log.info("消息发送完成，回调内容：{}", iMqttDeliveryToken.isComplete());
    }
}