package com.usky.ai.service.mqtt;

import com.usky.ai.service.enums.TopListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.endpoint.MessageProducerSupport;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;

import java.util.List;
import java.util.stream.Collectors;

@Configuration
public class MqttInConfig {

    public static final String CHANNEL_NAME_INPUT = "mqttInboundChannel";
    public static final String CHANNEL_BOARD_PING = "boardPingChannel";

    @Bean
    public MessageProducerSupport mqttInbound(MqttPahoClientFactory factory) {
        // 获取所有需要订阅的主题
        List<String> topics = TopListener.parse(1).stream()
                .map(TopListener::getCode)
                .collect(Collectors.toList()); // 使用 collect(Collectors.toList())

        // 创建适配器实例，订阅所有主题
        MqttPahoMessageDrivenChannelAdapter adapter =
                new MqttPahoMessageDrivenChannelAdapter(
                        "server-in", factory, topics.toArray(new String[0]));

        // 设置消息转换器
        adapter.setConverter(new DefaultPahoMessageConverter());
        // 设置 QoS
        adapter.setQos(1);
        // 设置完成超时时间
        adapter.setCompletionTimeout(5000);

        // 设置输出通道
        adapter.setOutputChannel(mqttInboundChannel());

        return adapter;
    }

    @Bean(name = CHANNEL_NAME_INPUT)
    public MessageChannel mqttInboundChannel() {
        return new DirectChannel();
    }

    @Bean(name = CHANNEL_BOARD_PING)
    public MessageChannel boardPingChannel() {
        return new DirectChannel();
    }
}