package com.seer.teach.netty.im.registry;


import com.seer.teach.netty.common.annotation.ImMessageType;
import com.seer.teach.netty.im.handler.im.ImMsgHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * @Author: Captain
 * @Description:
 * @Date: 2025-05-20 17:36
 */
@Component
public class TvImMessageHandlerRegistry {

    private final Map<Integer, ImMsgHandler> handlerMap = new ConcurrentHashMap<>();

    @Autowired
    public TvImMessageHandlerRegistry(List<ImMsgHandler> handlers) {
        for (ImMsgHandler handler : handlers) {
            ImMessageType annotation = handler.getClass().getAnnotation(ImMessageType.class);
            if (annotation != null) {
                int type = annotation.value();
                if (handlerMap.containsKey(type)) {
                    throw new IllegalStateException("重复注册的消息类型: " + type);
                }
                handlerMap.put(type, handler);
            }
        }
    }

    public ImMsgHandler getHandler(Integer type) {
        return handlerMap.get(type);
    }
}
