package com.heyu.api.data.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * @author chentiefeng
 * @date 2020/12/15 11:31
 */
@Component
public class SpringContextUtils implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
    private static String PROFILE = null;
    public SpringContextUtils() {
    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        SpringContextUtils.applicationContext = context;
    }

    public static <T> T getBean(Class<T> clazz) {
        return clazz == null ? null : applicationContext.getBean(clazz);
    }

    public static <T> T getBean(String beanId) {
        return beanId == null ? null : (T) applicationContext.getBean(beanId);
    }

    public static <T> T getBean(String beanName, Class<T> clazz) {
        if (null != beanName && !"".equals(beanName.trim())) {
            return clazz == null ? null : applicationContext.getBean(beanName, clazz);
        } else {
            return null;
        }
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static void publishEvent(ApplicationEvent event) {
        if (applicationContext != null) {
            applicationContext.publishEvent(event);
        }
    }

    /**
     * 获取当前环境
     * @return String
     */
    public static String getActiveProfile() {
        if (PROFILE == null && applicationContext !=null) {
            PROFILE = applicationContext.getEnvironment().getActiveProfiles()[0];
        }
        return PROFILE;
    }


    public static boolean hasBean(String name) {
        String[] beanNames = applicationContext.getBeanDefinitionNames();
        List<String> list = Arrays.asList(beanNames);
        return list.contains(name);
    }



    /**
     * 从环境变量中获取
     * @param key
     * @return
     */
    public static String getProperty(String key) {
        if (applicationContext != null) {
            return applicationContext.getEnvironment().getProperty(key);
        }
        return null;
    }


}
