package com.skr.mdm.api.equipment;

import com.skr.mdm.api.equipment.annotation.UserStrategy;
import com.skr.mdm.api.equipment.service.UserStrategyService;
import com.skr.mdm.enums.UserStrategyEnum;
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 2023-02-02 16:10
 */
@Component
@Slf4j
public class UserStrategyFactory implements BeanPostProcessor {

    private static final Map<Integer, UserStrategyService> USER_STRATEGY_MAP = new ConcurrentHashMap<>(16);

    public static UserStrategyService getStrategy(Integer strategyType) {
        return USER_STRATEGY_MAP.get(strategyType);
    }

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

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean.getClass().isAnnotationPresent(UserStrategy.class)) {
            UserStrategy annotation = bean.getClass().getAnnotation(UserStrategy.class);
            UserStrategyEnum userStrategyEnum = annotation.strategyType();
            USER_STRATEGY_MAP.put(userStrategyEnum.getStrategyType(), (UserStrategyService) bean);
        }
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
}
