package ink.wgink.common.component;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: SpringBeanUtil
 * @Description: Spring工具类
 * @Author: WangGeng
 * @Date: 2021/6/14 22:16
 * @Version: 1.0
 **/
@Component
public class SpringBeanUtil implements ApplicationContextAware {
    protected final static Logger logger = LoggerFactory.getLogger(SpringBeanUtil.class);

    private static ApplicationContext ctx = null;

    private static Map<String, Properties> propMap = new HashMap<>(0);

    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        SpringBeanUtil.ctx = ctx;
    }

    public ApplicationContext getApplicationContext() {
        return ctx;
    }

    public <T> T getBean(String prop) {
        Object obj = ctx.getBean(prop);
        if (logger.isDebugEnabled()) {
            logger.debug("property=[" + prop + "],object=[" + obj + "]");
        }
        return (T) obj;
    }

    public Properties getProperties(String filepath) {
        if (propMap.containsKey(filepath)) {
            return propMap.get(filepath);
        }
        Resource resource = ctx.getResource(filepath);
        Properties prop = new Properties();
        try {
            prop.load(resource.getInputStream());
            propMap.put(filepath, prop);
            return prop;
        } catch (IOException e) {
            logger.error("can not find the resource file:[" + filepath + "]", e);
            return null;
        }
    }

}
