package com.usky.eg.mqtt;

import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
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.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
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;

/**
 * 出站 MQTT（发布远程升级下行指令）。
 */
@Configuration
public class EgMqttOutboundConfig {

    public static final String CHANNEL_NAME_OUT = "egMqttOutboundChannel";
    public static final String DEFAULT_TOPIC = "eg/default";

    @Autowired
    private EgMqttProperties egMqttProperties;

    @Bean
    public MqttPahoClientFactory egMqttPahoClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions options = new MqttConnectOptions();
        options.setServerURIs(new String[]{egMqttProperties.getUrl()});
        String user = egMqttProperties.getUsername();
        if (user != null && !user.isEmpty()) {
            options.setUserName(user);
        }
        String pwd = egMqttProperties.getPassword();
        if (pwd != null && !pwd.isEmpty()) {
            options.setPassword(pwd.toCharArray());
        }
        factory.setConnectionOptions(options);
        return factory;
    }

    @Bean(name = CHANNEL_NAME_OUT)
    public MessageChannel egMqttOutboundChannel() {
        return new DirectChannel();
    }

    @Bean
    @ServiceActivator(inputChannel = CHANNEL_NAME_OUT)
    public MessageHandler egMqttOutbound(MqttPahoClientFactory egMqttPahoClientFactory) {
        String clientId = "service-eg-mqtt-out-" + System.currentTimeMillis();
        MqttPahoMessageHandler handler = new MqttPahoMessageHandler(clientId, egMqttPahoClientFactory);
        handler.setAsync(true);
        handler.setDefaultTopic(DEFAULT_TOPIC);
        return handler;
    }

    @MessagingGateway(defaultRequestChannel = CHANNEL_NAME_OUT)
    public interface EgMqttPublishGateway {

        void sendToMqtt(@Header(MqttHeaders.TOPIC) String topic, @Header(MqttHeaders.QOS) int qos, String payload);
    }
}
