package com.yeejoin.amos.boot.module.jg.biz.context;

import com.yeejoin.amos.boot.module.jg.api.service.IBizDataChangeHandleStrategy;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

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

/**
 * @author Administrator
 */
@Component
public class BizDataHandleStrategyContext implements ApplicationContextAware {

    private static final Map<String, IBizDataChangeHandleStrategy> dataProcessStrategyHashMap = new HashMap<>();

    public static IBizDataChangeHandleStrategy getStrategy(String bizType) {
        return Optional.ofNullable(dataProcessStrategyHashMap.get(bizType)).orElseThrow(() -> new RuntimeException(String.format("not found %s type strategy", bizType)));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, IBizDataChangeHandleStrategy> strategyBeans = applicationContext.getBeansOfType(IBizDataChangeHandleStrategy.class);
        if (strategyBeans.isEmpty()) {
            return;
        }
        for (IBizDataChangeHandleStrategy strategy : strategyBeans.values()) {
            dataProcessStrategyHashMap.put(strategy.canHandleBizType(), strategy);
        }
    }
}
