package com.prolog.rdc.tms.service.strategy;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

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

@Service
public class CostStrategyRuleHandlerContext implements ApplicationContextAware {

    @Autowired
    private ApplicationContext applicationContext;

    private static final Map<Integer,Class> COST_MAP = new HashMap<>();
    private static final Map<Integer,Class> INCOME_COST_MAP = new HashMap<>();
    private static final Map<Integer,Class> PAY_COST_MAP = new HashMap<>();

    public AbstractSplitStrategyRuleHandler getHandlerInstance(Integer settlementModel){
        Class clazz = COST_MAP.get(settlementModel);
        return (AbstractSplitStrategyRuleHandler) applicationContext.getBean(clazz);
    }

    public IncomeAbstractSplitStrategyRuleHandler getHandlerInstanceIncome(Integer settlementModel){
        Class clazz = INCOME_COST_MAP.get(settlementModel);
        return (IncomeAbstractSplitStrategyRuleHandler) applicationContext.getBean(clazz);
    }

    public PayAbstractSplitStrategyRuleHandler getHandlerInstancePay(Integer settlementModel){
        Class clazz = PAY_COST_MAP.get(settlementModel);
        return (PayAbstractSplitStrategyRuleHandler) applicationContext.getBean(clazz);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String,Object> beans = applicationContext.getBeansWithAnnotation(CostStrategyRuleHandler.class);
        if (beans.size() > 0) {
            for (Object serviceBean : beans.values()) {
                Integer settlementModel = serviceBean.getClass().getAnnotation(CostStrategyRuleHandler.class).value();
                COST_MAP.put(settlementModel, serviceBean.getClass());
            }
        }

        Map<String,Object> incomeBeans = applicationContext.getBeansWithAnnotation(IncomeCostStrategyRuleHandler.class);
        if (incomeBeans.size() > 0) {
            for (Object serviceBean : incomeBeans.values()) {
                Integer settlementModel = serviceBean.getClass().getAnnotation(IncomeCostStrategyRuleHandler.class).value();
                INCOME_COST_MAP.put(settlementModel, serviceBean.getClass());
            }
        }

        Map<String,Object> payBeans = applicationContext.getBeansWithAnnotation(PayCostStrategyRuleHandler.class);
        if (payBeans.size() > 0) {
            for (Object serviceBean : payBeans.values()) {
                Integer settlementModel = serviceBean.getClass().getAnnotation(PayCostStrategyRuleHandler.class).value();
                PAY_COST_MAP.put(settlementModel, serviceBean.getClass());
            }
        }
    }
}
