package com.gyee.dataadapter.config;

import cn.hutool.core.thread.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.io.UnsupportedEncodingException;

/**
 * 主要用来接收和处理订阅主题的消息
 */
@Slf4j
public class PushCallback implements MqttCallback {

    private static final int RETRY_INTERVAL_MILLIS = 3000; // 5秒重试间隔
    private static final int MAX_RETRIES = 500; // 最大重试次数

    private MqttServer mqttServer;

    public PushCallback(MqttServer mqttServer) {
        this.mqttServer = mqttServer;
    }


    public void connectionLost(Throwable cause) {
        log.info("---------------------连接断开，正在重连");
        int retries = 0;
        while (retries < MAX_RETRIES) {
            try {
                // 尝试连接到服务器
                mqttServer.init();
                log.info("连接成功！");
                break; // 成功连接后退出循环
            } catch (Exception e) {
                retries++;
                if (retries >= MAX_RETRIES) {
                    log.error("连接次数超限：" + e.getMessage());
                    return; // 退出程序
                }
                // 等待一段时间后再重试
                log.info(RETRY_INTERVAL_MILLIS + "ms后重连！");
                log.error(e.getMessage());
                ThreadUtil.sleep(RETRY_INTERVAL_MILLIS);
            }
        }
    }


    /**
     * 发送消息，消息到达后处理方法
     *
     * @param token
     */
    public void deliveryComplete(IMqttDeliveryToken token) {
        System.out.println("deliveryComplete---------" + token.isComplete());
    }


    /**
     * 接收所订阅的主题的消息并处理
     *
     * @param topic
     * @param message
     */
    public void messageArrived2(String topic, MqttMessage message) throws UnsupportedEncodingException {
        // subscribe后得到的消息会执行到这里面
        String result = new String(message.getPayload(), "UTF-8");
        System.out.println("接收消息主题 : " + topic);
        System.out.println("接收消息Qos : " + message.getQos());
        System.out.println("接收消息内容 : " + result);
        System.out.println(message.getPayload().toString());
        //这里可以针对收到的消息做处理，比如持久化
    }

    public void messageArrived(String topic, MqttMessage message) {
        /*DataConverterManager dm = new DataConverterManager(message.getPayload());
        System.out.print(LocalDateTime.now().getMinute() + ",");
        List<PointInfo> pis = dm.getPintInfos();
        for (PointInfo pi : pis) {
            if (!MqttCache.subData.containsKey(pi.getPath())) {
                MqttCache.subData.put(pi.getPath(), pi);
            } else {
                MqttCache.subData.replace(pi.getPath(), pi);
            }
        }*/
        DataConverterManager2 dm = new DataConverterManager2(message.getPayload());
        System.out.print(dm.getPointCount() + ",");
    }

}
