package org.springblade.mqtt;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class MqttService {

	@Value("${mqtt.broker.url}")
	private String brokerUrl;

	@Value("${mqtt.client.id}")
	private String clientId;

	@Value("${mqtt.username}")
	private String username;

	@Value("${mqtt.password}")
	private String password;

	@Value("${mqtt.topic.subscribe}")
	private String subscribeTopic;

	private IMqttClient mqttClient;

	private static final int MAX_RETRY_ATTEMPTS = 5;
	private static final long RETRY_DELAY_MS = 5000;

	public void connectAndSubscribe() {
		int retryAttempts = 0;
		boolean connected = false;

		while (!connected && retryAttempts < MAX_RETRY_ATTEMPTS) {
			try {
				mqttClient = new MqttClient(brokerUrl, clientId, new MemoryPersistence());

				MqttConnectOptions options = new MqttConnectOptions();
				// 无需设置用户名和密码

				mqttClient.setCallback(new MqttCallbackImpl());

				mqttClient.connect(options);

				mqttClient.subscribe(subscribeTopic);

				connected = true;
			} catch (MqttException e) {
				retryAttempts++;
				e.printStackTrace();
				System.out.println("连接MQTT服务器失败，第 " + retryAttempts + " 次重试，等待 " + RETRY_DELAY_MS + " 毫秒后再次尝试...");
				try {
					Thread.sleep(RETRY_DELAY_MS);
				} catch (InterruptedException ex) {
					ex.printStackTrace();
				}
			}
		}

		if (!connected) {
			System.out.println("经过 " + MAX_RETRY_ATTEMPTS + " 次重试后，仍无法连接到MQTT服务器，程序退出或采取其他处理措施。");
			// 这里可以根据实际需求选择抛出异常让程序终止，或者进行其他更复杂的处理，比如记录错误并继续运行但标记MQTT连接不可用等
		}
	}

	public void disconnect() {
		try {
			if (mqttClient!= null && mqttClient.isConnected()) {
				mqttClient.disconnect();
			}
		} catch (MqttException e) {
			e.printStackTrace();
		}
	}

	private class MqttCallbackImpl implements MqttCallback {

		@Override
		public void connectionLost(Throwable cause) {
			// 连接丢失时的处理逻辑，这里实现重连机制
			System.out.println("MQTT连接丢失，尝试重连...");
			while (true) {
				try {
					mqttClient.connect(new MqttConnectOptions());
					mqttClient.subscribe(subscribeTopic);
					System.out.println("重连成功");
					break;
				} catch (MqttException e) {
					System.out.println("重连失败，等待一段时间后再次尝试...");
					try {
						Thread.sleep(5000);
					} catch (InterruptedException ex) {
						ex.printStackTrace();
					}
				}
			}
		}

		@Override
		public void messageArrived(String topic, MqttMessage message) throws Exception {
			// 接收到消息时的处理逻辑
			System.out.println("收到消息: " + new String(message.getPayload()));
		}

		@Override
		public void deliveryComplete(IMqttDeliveryToken token) {
			// 消息发送完成的处理逻辑（如果有发送需求的话）
		}
	}
}
