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

import com.yeejoin.amos.boot.module.jg.biz.service.IChangeDataProcessStrategy;
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 DataProcessStrategyContext implements ApplicationContextAware {

    private static final Map<IBizDataChangeHandleStrategy.ModelType, IChangeDataProcessStrategy> dataProcessStrategyHashMap = new HashMap<>();


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

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