package com.usky.fire.service.config.mqtt;

import com.usky.fire.service.enums.TopListener;
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;

import java.util.List;

/**
 * @author yq
 * @date 2021/11/1 16:37
 */
@ConditionalOnProperty(prefix = "mqtt", value = {"enabled"}, havingValue = "true")
@Configuration
public class MqttInConfig {

    @Autowired
    private MqttBaseConfig mqttBaseConfig;

    public static final String CHANNEL_NAME_INPUT = "mqttInputChannel";

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


    /**
     * 消息订阅绑定-消费者
     *
     * @return
     */
    @Bean
    public MessageProducer inbound() {
        List<TopListener> parse = TopListener.parse(1);
        String[] tops = parse.stream().map(TopListener::getCode).toArray(String[]::new);
        String clientId = "h-backend-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;
    }
}
