package com.gci.boot.common.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * spring上下文工具
 *
 * @author chenzw
 * @date 2023/8/14
 */
public final class SpringContextUtil {

	private static ApplicationContext applicationContext;

	/**
	 * 初始化，注入ApplicationContext对象
	 */
	public static class Initializer implements ApplicationContextAware {

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

	}

	// 获取applicationContext
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	// 通过name获取 Bean.
	public static Object getBean(String name) {
		return getApplicationContext().getBean(name);

	}

	// 通过name获取 Bean.
	public static Object getBean(String name, Object... params) {
		return getApplicationContext().getBean(name, params);
	}

	// 通过class获取Bean.
	public static <T> T getBean(Class<T> clazz) {
		return getApplicationContext().getBean(clazz);
	}

	// 通过name,以及Clazz返回指定的Bean
	public static <T> T getBean(String name, Class<T> clazz) {
		return getApplicationContext().getBean(name, clazz);
	}

	// 判断bean是否是prototype.
	public static boolean isPrototype(String name) {
		return getApplicationContext().isPrototype(name);
	}

	public static Class getType(String name) {
		return getApplicationContext().getType(name);
	}

	public static String[] getBeanNamesForType(Class c) {
		return getApplicationContext().getBeanNamesForType(c);
	}


	/**
	 * 获取HttpServletRequest
	 */
	public static HttpServletRequest getHttpServletRequest() {
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		if(requestAttributes != null) {
			return requestAttributes.getRequest();
		}
		return null;
	}

	public static String getDomain(){
		HttpServletRequest request = getHttpServletRequest();
		StringBuffer url = request.getRequestURL();
		return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
	}

	public static String getOrigin(){
		HttpServletRequest request = getHttpServletRequest();
		return request.getHeader("Origin");
	}
}
