package com.fizz.business.service.hanle;

import com.fizz.business.anno.OpcMessageHandlerType;
import com.fizz.business.constants.enums.OpcMessageType;
import com.fizz.business.domain.msg.OpcMessage;
import com.fizz.business.service.OpcMessageHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class OpcMessageDispatcher {

    private final Map<OpcMessageType, OpcMessageHandler<? extends OpcMessage>> handlerMap = new HashMap<>();

    @Autowired
    public OpcMessageDispatcher(ApplicationContext context) {
        Map<String, OpcMessageHandler> beans = context.getBeansOfType(OpcMessageHandler.class);
        beans.values().forEach(handler -> {
            OpcMessageHandlerType annotation = handler.getClass().getAnnotation(OpcMessageHandlerType.class);
            if (annotation != null) {
                handlerMap.put(annotation.value(), handler);
            } else {
                throw new IllegalStateException("Handler " + handler.getClass().getSimpleName() + " 未标注 @OpcMessageHandlerType");
            }
        });
    }

    @SuppressWarnings("unchecked")
    public <T extends OpcMessage> void dispatch(OpcMessageType type, T message) {
        OpcMessageHandler<T> handler = (OpcMessageHandler<T>) handlerMap.get(type);
        if (handler != null) {
            handler.handle(message);
        } else {
            System.out.println("未注册的 OPC 消息类型: " + type);
        }
    }
}
