package com.skr.mdm.service;

import com.skr.mdm.annotation.CmdHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

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

/**
 * @author nfq
 * @date 2020/7/30 16:10
 */
@Slf4j
@Component
public class StrategyFactory implements BeanPostProcessor {

    private static final Map<Short, CmdHandlerService> CMD_MAP = new ConcurrentHashMap<>(128);

    public static CmdHandlerService getStrategy(short cmdType) {
        return CMD_MAP.get(cmdType);
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean.getClass().isAnnotationPresent(CmdHandler.class)) {
            CmdHandler annotation = bean.getClass().getAnnotation(CmdHandler.class);
            short[] cmdTypes = annotation.cmdType();
            for (short cmdType : cmdTypes) {
                CMD_MAP.put(cmdType, (CmdHandlerService) bean);
            }
        }
        return bean;
    }
}
