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


import com.github.pagehelper.util.StringUtil;
import com.yeejoin.amos.boot.module.ccs.api.service.MqttReceiveService;
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;

import java.util.ArrayList;
import java.util.List;

/**
 * @author keyong
 * @title: CcsMqttReceiveConfig
 * <pre>
 * @description: MQTT订阅模式消费类
 * </pre>
 * @date 2020/10/29 19:23
 */
@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}")
    private String defaultTopic;

//    @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(), defaultTopic);
//        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();
//            int endIndex = topic.lastIndexOf("/");
//            if (endIndex > 0 && StringUtil.isNotEmpty(String.valueOf(message))) {
//                String dataType = topic.substring(endIndex + 1);
//                if (dataType.equals("property") && StringUtil.isNotEmpty(msg)) {
            mqttReceiveService.handlerMqttIncrementMessage(topic, msg);
//                }
//            }
        };
    }
}
