package com.yida.data.attendance.utils;

import cn.hutool.core.util.StrUtil;
import com.yida.data.attendance.constant.MqttConstant;
import com.yida.data.attendance.service.impl.HaiqingCallbackService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.context.annotation.Configuration;

@Configuration
@Slf4j
public class MqttUtil {

    private static MqttClient mqttClient;
    private static final String MQTT_CLIENT_ID = StrUtil.uuid();

    public MqttUtil(HaiqingCallbackService haiqingCallbackService, MqttConstant mqttConstant) {
        MemoryPersistence memoryPersistence = new MemoryPersistence();
        try {
            mqttClient = new MqttClient(mqttConstant.getUrl(), MQTT_CLIENT_ID,
                memoryPersistence);
            // 设置回调函数，当订阅到信息时调用此方法
            mqttClient.setCallback(haiqingCallbackService);
            // 向回调添加此客户端
            haiqingCallbackService.setMqttUtil(this);
            MqttConnectOptions connOpts = new MqttConnectOptions();
            // 不自动清除session，每次连接会消费离线期间积累的消息
            connOpts.setCleanSession(true);
            connOpts.setAutomaticReconnect(true);
            //connOpts.setConnectionTimeout(10);
            connOpts.setKeepAliveInterval(20);
            connOpts.setUserName(mqttConstant.getUsername());
            connOpts.setPassword(mqttConstant.getPassword().toCharArray());
            connOpts.setAutomaticReconnect(true);
            mqttClient.connect(connOpts);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("error:{}", e.getMessage());
        }
    }


    public Boolean pulish(String msg, String topic) {
        try {
            mqttClient.publish(topic, new MqttMessage(msg.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public Boolean addTopic(String topic) {
        try {
            mqttClient.subscribe(topic, 2);
        } catch (Exception e) {
            log.error("msg:{}", e.getMessage());
            return false;
        }
        return true;
    }

    public Boolean addTopic(String[] topic) {
        try {
            // 保证一定只接受一次消息
            int[] qos = new int[topic.length];
            for (int i = 0; i < topic.length; i++) {
                qos[i] = 2;
            }
            mqttClient.subscribe(topic, qos);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("msg:{}", e.getMessage());
            return false;
        }
        return true;
    }

}
