package com.usky.ai.service.mqtt;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

@Configuration
@IntegrationComponentScan
@ConditionalOnProperty(prefix = "mqtt", value = {"enabled"}, havingValue = "true")
public class MqttOutConfig {

    @Autowired
    public MqttBaseConfig mqttBaseConfig;

    public static final String CHANNEL_NAME_OUT = "mqttOutboundChannel";
    public static final String MESSAGE_NAME = "messageOut";
    public static final String DEFAULT_TOPIC = "testTopic";

    @Bean(name = CHANNEL_NAME_OUT)
    public MessageChannel mqttOutboundChannel() {
        return new DirectChannel();
    }

    @Bean(name = MESSAGE_NAME)
    @ServiceActivator(inputChannel = CHANNEL_NAME_OUT)
    public MessageHandler outbound() {
        String clientId = "h-backend-mqtt-out-" + System.currentTimeMillis();
        MqttPahoMessageHandler messageHandler =
                new MqttPahoMessageHandler(clientId, mqttBaseConfig.mqttClientFactory());
        messageHandler.setAsync(true);
        messageHandler.setDefaultTopic(DEFAULT_TOPIC);
        return messageHandler;
    }
}
