package net.northking.cctp.element.core.support;

import net.northking.cctp.element.util.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * DefaultBeanFactory
 *
 * @author fengxiang.zhang
 * @since 1.0
 */
public class DefaultBeanFactory implements BeanFactory, BeanRegistry {

    private static Logger logger = LoggerFactory.getLogger(DefaultBeanFactory.class);
    private Map<Class<?>, Object> beanCache = new ConcurrentHashMap<>(16);

    @Override
    public <T> T getBean(Class<T> requiredType) {
        return (T) beanCache.get(requiredType);
    }

    @Override
    public Collection<Object> getAllBeans() {
        return beanCache.values();
    }

    @Override
    public void registerBeans(Class<?>... clazz) {
        Assert.notNull(clazz);
        for (Class<?> cls : clazz) {
            try {
                beanCache.put(cls, cls.newInstance());
                logger.debug("Register bean {} instance ", cls);
            } catch (Exception e) {
                logger.error("Register {} bean error: {}", cls, e);
            }
        }
    }

    @Override
    public void registerBean(Class<?> cls, Object bean) {
        Assert.notNull(cls);
        Assert.notNull(bean);
        if (cls.isAssignableFrom(bean.getClass())) {
            beanCache.put(cls, bean);
            logger.debug("Register bean {} ", bean.getClass());
        }
    }
}
