package com.ho.datacollect.config;

import cn.hutool.core.util.IdUtil;
import com.ho.datacollect.util.MqttConfigUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author yule
 * @desc: Mqtt配置类
 * @date 2022/11/7
 */
@Configuration
@Data
@ConfigurationProperties("mqtt")
@Slf4j
public class MqttConfig {

    //服务器url
    String url;
    //用户名
    String userName;
    //密码
    String passWord;
    //超时时间
    Integer timeout;
    //会话保持时间
    Integer keepAlive;

    @Value("${topic.edgeLoginRequest}")
    String edgeLoginRequest;

    @Value("${topic.edgeReadResponse}")
    String edgeReadResponse;

    @Value("${topic.edgeWriteResponse}")
    String edgeWriteResponse;

    @Value("${topic.edgeReportPush}")
    String edgeReportPush;

    @Value("${topic.edgeControlResponse}")
    String edgeControlResponse;

    @Autowired
    LoginRequestConsumer loginRequestConsumer;

    @Autowired
    ReadResponseConsumer readResponseConsumer;

    @Autowired
    WriteResponseConsumer writeResponseConsumer;

    @Autowired
    ReportPushConsumer reportPushConsumer;

    @Autowired
    ControlResponseConsumer controlResponseConsumer;

    //是否自动重连 实际环境要改为true
    private boolean autoReConnect = true;


    //登录验证的监听
    @Bean(name = "LoginRequest")
    public MqttClient initLoginRequest() {
        String clientId = IdUtil.simpleUUID();
        log.info("clientId:" +clientId);
        MqttClient client =null;
        try {
            client = new MqttClient(url, clientId,null);
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(userName);
            options.setPassword(passWord.toCharArray());
            options.setCleanSession(true);
            options.setConnectionTimeout(timeout);
            options.setKeepAliveInterval(keepAlive);
            options.setExecutorServiceTimeout(0);
            //options.setAutomaticReconnect(autoReConnect);
            client.setCallback(loginRequestConsumer);
            IMqttToken iMqttToken = client.connectWithResult(options);
            boolean complete = iMqttToken.isComplete();
            log.info("LoginRequestMqttClient建立连接：{}", complete);
            //这里监听的是
            String[] topic = MqttConfigUtil.getLoginRequestTopic();
            int[] qos = new int[topic.length];
            client.subscribe(topic,qos);
            log.info("已订阅topic：{}", topic);
            return client;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return client;
    }

    //读取文件请求的监听
    @Bean(name = "ReadResponse")
    public MqttClient initReadRequest() {
        String clientId = IdUtil.simpleUUID();
        log.info("clientId:" +clientId);
        MqttClient client =null;
        try {
            client = new MqttClient(url, clientId,null);
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(userName);
            options.setPassword(passWord.toCharArray());
            options.setCleanSession(true);
            options.setConnectionTimeout(timeout);
            options.setKeepAliveInterval(keepAlive);
            options.setExecutorServiceTimeout(0);
            //options.setAutomaticReconnect(autoReConnect);
            client.setCallback(readResponseConsumer);
            IMqttToken iMqttToken = client.connectWithResult(options);
            boolean complete = iMqttToken.isComplete();
            log.info("ReadRequestMqttClient建立连接：{}", complete);
            //这里监听的是
            String[] topic = MqttConfigUtil.getReadRequestTopic();
            int[] qos = new int[topic.length];
            client.subscribe(topic,qos);
            log.info("已订阅topic：{}", topic);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return client;
    }

    //写文件响应的监听
    @Bean(name = "WriteResponse")
    public MqttClient initWriteRequest() {
        String clientId = IdUtil.simpleUUID();
        log.info("clientId:" +clientId);
        MqttClient client =null;
        try {
            client = new MqttClient(url, clientId,null);
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(userName);
            options.setPassword(passWord.toCharArray());
            options.setCleanSession(true);
            options.setConnectionTimeout(timeout);
            options.setKeepAliveInterval(keepAlive);
            options.setExecutorServiceTimeout(0);
            //options.setAutomaticReconnect(autoReConnect);
            client.setCallback(writeResponseConsumer);
            IMqttToken iMqttToken = client.connectWithResult(options);
            boolean complete = iMqttToken.isComplete();
            log.info("WriteRequestMqttClient建立连接：{}", complete);
            //这里监听的是
            String[] topic = MqttConfigUtil.getWriteRequestTopic();
            int[] qos = new int[topic.length];
            client.subscribe(topic,qos);
            log.info("已订阅topic：{}", topic);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return client;
    }

    //报告上传
    @Bean(name = "ReportPush")
    public MqttClient initReportPush() {
        String clientId = IdUtil.simpleUUID();
        log.info("clientId:" +clientId);
        MqttClient client =null;
        try {
            client = new MqttClient(url, clientId,null);
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(userName);
            options.setPassword(passWord.toCharArray());
            options.setCleanSession(true);
            options.setConnectionTimeout(timeout);
            options.setKeepAliveInterval(keepAlive);
            options.setExecutorServiceTimeout(0);
            //options.setAutomaticReconnect(autoReConnect);
            client.setCallback(reportPushConsumer);
            IMqttToken iMqttToken = client.connectWithResult(options);
            boolean complete = iMqttToken.isComplete();
            log.info("ReportPushMqttClient建立连接：{}", complete);
            //这里监听的是
            String[] topic = MqttConfigUtil.getReportPushTopic();
            int[] qos = new int[topic.length];
            client.subscribe(topic,qos);
            log.info("已订阅topic：{}", topic);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return client;
    }

    //远程控制
    @Bean(name = "ControlResponse")
    public MqttClient initControlResponse() {
        String clientId = IdUtil.simpleUUID();
        log.info("clientId:" +clientId);
        MqttClient client =null;
        try {
            client = new MqttClient(url, clientId,null);
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(userName);
            options.setPassword(passWord.toCharArray());
            options.setCleanSession(true);
            options.setConnectionTimeout(timeout);
            options.setKeepAliveInterval(keepAlive);
            options.setExecutorServiceTimeout(0);
            //options.setAutomaticReconnect(autoReConnect);
            client.setCallback(controlResponseConsumer);
            IMqttToken iMqttToken = client.connectWithResult(options);
            boolean complete = iMqttToken.isComplete();
            log.info("ControlResponseMqttClient建立连接：{}", complete);
            //这里监听的是
            String[] topic = MqttConfigUtil.getControlResponseTopic();
            int[] qos = new int[topic.length];
            client.subscribe(topic,qos);
            log.info("已订阅topic：{}", topic);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return client;
    }

}
