package com.yeejoin.amos.boot.module.ccs.biz.config;


import com.yeejoin.amos.boot.module.ccs.api.service.MqttReceiveService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
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.IntegrationComponentScan;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

@Slf4j
@Configuration
@IntegrationComponentScan
public class CcsMqttReceiveConfig {


    @Value("${emqx.user-name}")
    private String userName;

    @Value("${emqx.password}")
    private String password;

    @Value("${emqx.broker}")
    private String hostUrl;

    @Value("${emqx.client-id}")
    private String clientId;

    @Value("${mqtt.topic.alarm}")
    private String alarmTopic;

    @Value("${mqtt.topic.question}")
    private String questionTopic;


//    @Value("${spring.mqtt.completionTimeout}")
//    private int completionTimeout;

    // 全局变量adapter
    public MqttPahoMessageDrivenChannelAdapter adapter;

    @Autowired
    public MqttReceiveService mqttReceiveService;


    @Bean
    public MqttConnectOptions getMqttConnectOptions() {
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setUserName(userName);
        mqttConnectOptions.setPassword(password.toCharArray());
        mqttConnectOptions.setServerURIs(new String[]{hostUrl});
        mqttConnectOptions.setKeepAliveInterval(20);
        mqttConnectOptions.setAutomaticReconnect(true);
//        mqttConnectOptions.setConnectionTimeout(0);
        return mqttConnectOptions;
    }

    @Bean
    public MqttPahoClientFactory mqttPahoClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        factory.setConnectionOptions(getMqttConnectOptions());
        return factory;
    }

    // 接收通道
    @Bean
    public MessageChannel mqttInputChannel() {
        return new DirectChannel();
    }

    //配置client,监听的topic
    @Bean
    public MessageProducer inbound() {
        adapter = new MqttPahoMessageDrivenChannelAdapter(clientId, mqttPahoClientFactory(), alarmTopic, questionTopic);
//        adapter.setCompletionTimeout(completionTimeout);
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setQos(0);
        adapter.setOutputChannel(mqttInputChannel());
        return adapter;
    }

    //通过通道获取数据
    @Bean
    @ServiceActivator(inputChannel = "mqttInputChannel")
    public MessageHandler handler() {
        return message -> {
            String topic = message.getHeaders().get("mqtt_receivedTopic").toString();
            String msg = message.getPayload().toString();
            log.info("message内容：{}", msg);
            if (alarmTopic.equals(topic)) {
                mqttReceiveService.handlerMqttAlarmMessage(topic, msg);
            } else if (questionTopic.equals(topic)) {
                mqttReceiveService.handlerMqttQuestionMessage(topic, msg);
            }
        };
    }
}
