package com.usky.iot.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.annotation.MessagingGateway;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.handler.annotation.Header;

@ConditionalOnProperty(prefix = "mqtt", value = {"enabled"}, havingValue = "true")
@Configuration
public class MqttOutConfig {

    @Autowired
    public MqttBaseConfig mqttBaseConfig;

    public static final String CHANNEL_NAME_OUT = "mqttOutboundChannel";

    public static final String MESSAGE_NAME = "messageOut";

    public static final String DEFAULT_TOPIC = "testTopic";

    /**
     * 连接通道
     *
     * @return
     */
    @Bean(name = CHANNEL_NAME_OUT)
    public MessageChannel mqttOutboundChannel() {
        return new DirectChannel();
    }

    /**
     * 发送消息和消费消息Channel可以使用相同MqttPahoClientFactory
     *
     * @return
     */
    @Bean(name = MESSAGE_NAME)
    @ServiceActivator(inputChannel = CHANNEL_NAME_OUT)
    public MessageHandler outbound() {
        // 在这里进行mqttOutboundChannel的相关设置
        String clientId = "h-backend-mqtt-out-" + System.currentTimeMillis();
        MqttPahoMessageHandler messageHandler =
                new MqttPahoMessageHandler(clientId, mqttBaseConfig.mqttClientFactory());
        //如果设置成true，发送消息时将不会阻塞。
        messageHandler.setAsync(true);
        messageHandler.setDefaultTopic(DEFAULT_TOPIC);
        return messageHandler;
    }

    @MessagingGateway(defaultRequestChannel = CHANNEL_NAME_OUT)
    public interface MqttGateway {
        /**
         * 发送消息
         *
         * @param payload
         */
        void sendToMqtt(String payload);

        /**
         * 指定top发送消息
         *
         * @param topic
         * @param payload
         */
        void sendToMqtt(@Header(MqttHeaders.TOPIC) String topic, String payload);

        /**
         * 指定队列和qos
         *
         * @param topic
         * @param qos
         * @param payload
         */
        void sendToMqtt(@Header(MqttHeaders.TOPIC) String topic, @Header(MqttHeaders.QOS) int qos, String payload);
    }
}
