package com.fuyuanshen.global.mqtt.config;

import cn.hutool.core.lang.UUID;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

@Configuration
@Slf4j
public class MqttOutboundConfiguration {
    @Autowired
    private MqttPropertiesConfig mqttPropertiesConfig;
    @Autowired
    private MqttPahoClientFactory mqttPahoClientFactory;
 
    // 消息通道
    @Bean
    public MessageChannel mqttOutboundChannel(){
        return new DirectChannel();
    }


    /** 配置出站消息处理器 */
    @Bean
    @ServiceActivator(inputChannel = "mqttOutboundChannel")  // 指定处理器针对哪个通道的消息进行处理
    public MessageHandler mqttOutboundMessageHandler(){
        String clientId = mqttPropertiesConfig.getPubClientId() + "_" + UUID.fastUUID();
        MqttPahoMessageHandler mqttPahoMessageHandler = new MqttPahoMessageHandler(
                mqttPropertiesConfig.getUrl(),
                clientId,
                mqttPahoClientFactory
        );
        mqttPahoMessageHandler.setDefaultQos(1);
        mqttPahoMessageHandler.setDefaultTopic("B/#");
        mqttPahoMessageHandler.setAsync(true);
        return mqttPahoMessageHandler;
    }
 
}