package com.yupi.project.mqtt;

import com.yupi.project.config.properties.MqttLoggerProperties;
import lombok.RequiredArgsConstructor;
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.MqttException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class MqttLoggerConnectionManager implements ApplicationListener<ContextRefreshedEvent>, DisposableBean {

    @Qualifier("mqttLoggerClient")
    private final MqttClient mqttLoggerClient; // 注入日志专用客户端
    private final MqttConnectOptions mqttConnectOptions; // 可复用主连接配置
    private final MqttLoggerProperties mqttLoggerProperties;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext().getParent() == null) { // Ensure root context
            if (mqttLoggerProperties.isEnabled() && mqttLoggerClient != null) {
                connectToMqtt();
            }
        }
    }

    private void connectToMqtt() {
        try {
            if (!mqttLoggerClient.isConnected()) {
                log.info("Attempting to connect MQTT Logger Client: {} to broker: {}", mqttLoggerClient.getClientId(), mqttLoggerClient.getServerURI());
                mqttLoggerClient.connect(mqttConnectOptions);
                // Subscription logic is handled by MqttLoggerCallbackHandler.connectComplete
            } else {
                log.info("MQTT Logger Client {} is already connected.", mqttLoggerClient.getClientId());
            }
        } catch (MqttException e) {
            log.error("Error connecting MQTT Logger Client: ", e);
        } catch (Exception e) {
            log.error("Unexpected error during MQTT Logger Client connection: ", e);
        }
    }

    @Override
    public void destroy() throws Exception {
        if (mqttLoggerProperties.isEnabled() && mqttLoggerClient != null) {
            disconnectFromMqtt();
        }
    }

    private void disconnectFromMqtt() {
        try {
            if (mqttLoggerClient.isConnected()) {
                log.info("Disconnecting MQTT Logger Client: {} from broker: {}", mqttLoggerClient.getClientId(), mqttLoggerClient.getServerURI());
                mqttLoggerClient.disconnect();
                log.info("MQTT Logger Client {} disconnected successfully.", mqttLoggerClient.getClientId());
            }
        } catch (MqttException e) {
            log.error("Error disconnecting MQTT Logger Client: ", e);
        } finally {
            try {
                log.info("Closing MQTT Logger Client: {}", mqttLoggerClient.getClientId());
                mqttLoggerClient.close();
                log.info("MQTT Logger Client {} closed successfully.", mqttLoggerClient.getClientId());
            } catch (MqttException e) {
                log.error("Error closing MQTT Logger Client: ", e);
            }
        }
    }
} 