package com.ruoyi.dj.mqtt.service;

import com.ruoyi.dj.mqtt.handler.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Component
public class MqttMessageService {

    private final Map<String, BiConsumer<String, String>> messageHandlers = new HashMap<>();

    @Autowired
    private OSDHandler osdHandler;

    @Autowired
    private StateHandler stateHandler;

    @Autowired
    private ServicesReplyHandler servicesReplyHandler;

    @Autowired
    private EventsHandler eventsHandler;

    @Autowired
    private RequestsHandler requestsHandler;

    @Autowired
    private StatusHandler statusHandler;

    @Autowired
    private PropertySetReplyHandler propertySetReplyHandler;

    @Autowired
    private DrcUpHandler drcUpHandler;

    @PostConstruct
    public void init() {
        initMessageHandlers();
    }

    /**
     * 初始化消息接收的处理函数
     */
    private void initMessageHandlers() {
        messageHandlers.put("thing/product/+/osd", osdHandler::handle);
        messageHandlers.put("thing/product/+/state", stateHandler::handle);
        messageHandlers.put("thing/product/+/services_reply", servicesReplyHandler::handle);
        messageHandlers.put("thing/product/+/events", eventsHandler::handle);
        messageHandlers.put("thing/product/+/requests", requestsHandler::handle);
        messageHandlers.put("sys/product/+/status", statusHandler::handle);
        messageHandlers.put("thing/product/+/property/set_reply", propertySetReplyHandler::handle);
        messageHandlers.put("thing/product/+/drc/up", drcUpHandler::handle);
    }

    /**
     * 调度到具体的处理器
     *
     * @param topic
     * @param message
     */
    public void handleMessage(String topic, String message) {
        for (Map.Entry<String, BiConsumer<String, String>> entry : messageHandlers.entrySet()) {
            String pattern = entry.getKey().replace("+", "([^/]+)");
            Pattern regex = Pattern.compile(pattern);
            Matcher matcher = regex.matcher(topic);
            if (matcher.matches()) {
                String matchedPart = matcher.group(1); // 获取匹配 + 的部分
                try {
                    entry.getValue().accept(matchedPart, message);
                } catch (Exception e) {
                    log.error("处理消息时发生错误, 主题: " + topic + ", 消息: " + message, e);
                }
                return;
            }
        }
    }
}
