package com.yzt.airconditionersystem.config;

import com.yzt.airconditionersystem.service.MqttService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.core.MessageProducer;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;

/**
 * @author TzZach
 * @since 2022-06-29 13:59
 */
@Configuration
public class MqttInboundConfig {

    @Value("${spring.mqtt.url}")
    private String url;

    @Value("${spring.mqtt.consumerClientId}")
    private String consumerClientId;

    @Value("${spring.mqtt.consumerTopic}")
    private String consumerTopic;

    @Value("${spring.mqtt.timeout}")
    private Long timeout;

    @Value("${spring.mqtt.qos}")
    private Integer qos;

    @Autowired
    private MqttService mqttService;

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

    @Bean
    public MessageProducer inbound() {
        MqttPahoMessageDrivenChannelAdapter adapter =
                new MqttPahoMessageDrivenChannelAdapter(url, consumerClientId, consumerTopic);
        adapter.setCompletionTimeout(timeout);
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setQos(qos);
        adapter.setOutputChannel(mqttInputChannel());
        return adapter;
    }

    @Bean
    @ServiceActivator(inputChannel = "mqttInputChannel")
    public MessageHandler handler() {
        return new MessageHandler() {
            @Override
            public void handleMessage(Message<?> message) throws MessagingException {
                String topic = (String) message.getHeaders().get(MqttHeaders.RECEIVED_TOPIC);
                try {
                    mqttService.receiveFrom(topic , message);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        };
    }

}
