package com.multictrl.modules.business.handler;

import cn.hutool.core.util.StrUtil;
import com.multictrl.common.constant.BusinessConstant;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * mqtt client1主题分发器
 *
 * @author Sdy
 * @since 1.0.0 2026/4/22
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class TopicDistributor {
    private final RequestsHandler requestsHandler;
    private final StatusHandler statusHandler;
    private final OsdHandler osdHandler;
    private final StateHandler stateHandler;
    private final ServicesReplyHandler servicesReplyHandler;
    private final EventsHandler eventsHandler;
    private final Map<String, MessageHandler> handlerMap = new ConcurrentHashMap<>();

    @PostConstruct
    public void init() {
        handlerMap.put(BusinessConstant.REQUESTS, requestsHandler);
        handlerMap.put(BusinessConstant.STATUS, statusHandler);
        handlerMap.put(BusinessConstant.OSD, osdHandler);
        handlerMap.put(BusinessConstant.STATE, stateHandler);
        handlerMap.put(BusinessConstant.EVENTS, eventsHandler);
        handlerMap.put(BusinessConstant.SERVICES_REPLY, servicesReplyHandler);
    }

    public void route(String topic, String payload) {
        String method = StrUtil.subAfter(topic, "/", true);
        String gateway = StrUtil.subAfter(StrUtil.subBefore(topic, "/", true),
                "/", true);
        MessageHandler handler = handlerMap.get(method);
        if (handler != null) {
            handler.handleMessage(topic, payload, gateway);
        } else {
//            log.error("未找到对应的处理器: {}", topic);
        }
    }
}
