package com.usky.cdi.service.config.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.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;

/**
 * @author han
 * @date 2025/03/20 14:30
 */
public class MqttInConfig {
    public MqttBaseConfig mqttBaseConfig;

    public static final String CHANNEL_NAME_INPUT = "mqttInputChannel";

    public MessageChannel mqttInputChannel() {
        return new DirectChannel();
    }


    /**
     * 消息订阅绑定-消费者
     *
     * @return
     */
    public MessageProducer inbound() {
        String msgTopic = mqttBaseConfig.getMsgTopic();
        if (msgTopic == null || msgTopic.trim().isEmpty()) {
            throw new IllegalStateException("MQTT订阅主题配置不能为空");
        }
        String[] tops = msgTopic.split(",");
        String clientId = "h-agbox-mqtt-in-" + System.currentTimeMillis();
        MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(clientId,
                mqttBaseConfig.mqttClientFactory(), tops);
        adapter.setCompletionTimeout(mqttBaseConfig.getCompletionTimeout());
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setQos(2);
        adapter.setOutputChannel(mqttInputChannel());
        return adapter;
    }
}
