package cc.smtweb.framework.core.mvc.controller.binder;

import cc.smtweb.framework.core.mvc.controller.IBeanContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;

import java.util.Map;

public class BeanContext implements IBeanContext {
    private final Map<Class<?>, Object> beanMap;
    private final BeanFactory applicationContext;

    public BeanContext(Map<Class<?>, Object> beanMap, BeanFactory applicationContext) {
        this.beanMap = beanMap;
        this.applicationContext = applicationContext;
    }

    @Override
    public <T> T getBean(String name, Class<T> type) throws BeansException {
        Object controllerAccess = beanMap.get(type);

        if (controllerAccess == null) {
            return applicationContext.getBean(name, type);
        } else {
            return (T) controllerAccess;
        }
    }

    @Override
    public <T> T getBean(Class<T> type) throws BeansException {
        Object controllerAccess = beanMap.get(type);

        if (controllerAccess != null) {
            return (T) controllerAccess;
        }

        controllerAccess = applicationContext.getBean(type);
        if (controllerAccess != null) {
            return (T) controllerAccess;
        }

        return null;
    }

    public void init() {
    }
}
