package com.gxwebsoft.hjm.controller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
* @Description:
 * maven 依赖：
 * 		<dependency>
 * 			<groupId>org.eclipse.paho</groupId>
 * 			<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
 * 			<version>1.2.1</version>
 * 		</dependency>
 *
* @Author: lx
* @Version: 1.0.0
* @Date: 2025/7/2
*/
public class MQTTClientDemo {

    private static final Log log = LogFactory.getLog(MQTTClientDemo.class);

    private MqttClient client;

    private  String HOST = "TCP://127.0.0.1:1883";
    private String userName = "";
    private String passWord = "";
    private String mqttClientId="";
    private MqttCallback callback;


    public MQTTClientDemo(MqttCallback callback, String host,String clientId,String usrname,String password) throws MqttException {
        this.callback = callback;
        HOST = host;
        mqttClientId = clientId;
        userName = usrname;
        passWord = password;

        client = new MqttClient(HOST, mqttClientId, new MemoryPersistence());
        connect();
    }

    /**
     *  用来连接服务器
     */
    public void connect() {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(false);
        options.setUserName(userName);
        options.setPassword(passWord.toCharArray());
        // 设置超时时间
        options.setConnectionTimeout(10);
        // 设置会话心跳时间
        options.setKeepAliveInterval(20);
        //设置自动重连
        options.setAutomaticReconnect(true);
        try {
            System.out.println("DC MQTT Host="+HOST);
            System.out.println("DC MQTT ClientId="+mqttClientId);
            System.out.println("DC MQTT userName="+userName);
            System.out.println("DC MQTT passWord="+passWord);
            client.setCallback(this.callback);
            client.connect(options);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public MqttTopic getTopic(String topic) {
        return client.getTopic(topic);
    }

    public void subscribe(String topic) throws MqttException {
        client.subscribe(topic);
    }

    public void subscribe(String[] topics) throws MqttException {
        client.subscribe(topics);
    }

    //qos 0：最多一次 、1：最少一次 、2：只有一次
    public void subscribe(String topic,int qos) throws MqttException {
        client.subscribe(topic,qos);
    }

    public void subscribe(String[] topics,int[] qosArr) throws MqttException {
        client.subscribe(topics,qosArr);
    }

    /**
     *
     * @param topic
     * @param message
     * @throws MqttPersistenceException
     * @throws MqttException
     */
    public void publish(MqttTopic topic , MqttMessage message) throws MqttPersistenceException,
            MqttException {
        MqttDeliveryToken token = topic.publish(message);
        /*
        //原地等待发送结果
        token.waitForCompletion();
        if(token.isComplete()) {
            log.info("message is published completely! ");
        }else {
        	log.info("message is published failed! ");
        }
        */
    }

    public void publish(MqttTopic topic,String payload,int qos,boolean retained) throws MqttPersistenceException, MqttException {
        MqttMessage msg = new MqttMessage();
        msg.setQos(qos);
        msg.setRetained(retained);
        msg.setPayload(payload.getBytes());
        publish(topic,msg);
    }

    public boolean isConnected() {
        return client.isConnected();
    }


    public static void main(String[] args) throws MqttException {
        MQTTClientDemo mqttClient = new MQTTClientDemo(new MqttCallback() {
            @Override
            public void connectionLost(Throwable throwable) {
                log.error("connectionLost...");
            }
            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                if (topic.equals("xxxxx")){
                    /*是指定topic*/
                }
                log.debug("DC 接收消息主题 : " + topic);
                log.debug("DC 接收消息Qos : " + message.getQos());
                log.debug("DC 接收消息内容 : " + new String(message.getPayload()));
            }
            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
                log.error("deliveryComplete..." + token.isComplete());
            }
        },"HOST", "SERVER_" + System.currentTimeMillis(), "userName", "passWord");
        /*订阅一个*/
        mqttClient.subscribe("TOPIC");
//        mqttClient.subscribe(new String[] {"TOPIC"});
    }
}
