package cn.estsh.i3plus.ext.mes.pcn.apiservice.config;


import cn.estsh.i3plus.ext.mes.pcn.api.base.IMesEquipmentLogService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.mqtt.PcnMqttClient;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.base.MesEquipmentLogService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.util.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.List;

@ConditionalOnExpression("'${pcn.mqtt.flag:false}' == 'true'")
@Slf4j
@Configuration
public class MqttConfig {

    @Value("${mqtt.host}")
    public String host;
    @Value("${mqtt.username}")
    public String username;
    @Value("${mqtt.password}")
    public String password;
    @Value("${mqtt.clientId}")
    public String clientId;
    @Value("${mqtt.timeout}")
    public int timeOut;
    @Value("${mqtt.keepalive}")
    public int keepAlive;

    @Value("${mqtt.clearSession}")
    public boolean clearSession;
    @Value("${mqtt.topic.list}")
    private String topicList;

    @Bean//注入Spring
    public PcnMqttClient myMqttClient() {
        PcnMqttClient myMqttClient = new PcnMqttClient(host, username, password, clientId, timeOut, keepAlive, clearSession);
        //手动注入
        MesEquipmentLogService service = SpringUtils.getBean(MesEquipmentLogService.class);

        myMqttClient.setService(service);
        for (int i = 0; i < 10; i++) {
            try {
                List<String> list =  Arrays.asList(topicList.split(","));
                myMqttClient.connect();
                list.forEach(topic -> myMqttClient.subscribe(topic));
                log.info("== PcnStartSystemInit ==> 订阅主题成功，topicList：{}", topicList);

            } catch (MqttException e) {
                log.error("== PcnStartSystemInit ==> MQTT connect exception, connect time = {}", i);
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
        }

        return myMqttClient;
    }

}
