package com.hotent.assembly.mockmvc;

import org.springframework.context.ApplicationContext;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import com.hotent.assembly.mockmvc.client.MockMvcClient;

import feign.Client;

/**
 *
 */
public class MockMvcFeignObjectWrapper {

	private final ApplicationContext applicationContext;

	private static MockMvc mockMvc;

	private static MockMvcClient mockMvcClient;

	public MockMvcFeignObjectWrapper(ApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
	}

	/**
	 * 如果当前的feignClient 不是MockMvcClient 转到MockMvcClient
	 * 
	 * @param bean
	 * @return
	 */
	Object wrap(Object bean) {
		if (bean instanceof Client && !(bean instanceof MockMvcClient)) {
			return getMockMvcClient(applicationContext);
		}
		return bean;
	}

	/**
	 * 构造MockMvc对象 单例 由于只有系统启动时 才会调用一次 不会存在并发 不需要考虑并发产生多个实例的问题
	 * 
	 * @return
	 */
	private static MockMvc getMockMvc(ApplicationContext applicationContext) {
		if (mockMvc == null) {
			mockMvc = MockMvcBuilders.webAppContextSetup((WebApplicationContext) applicationContext).build();
		}
		return mockMvc;
	}

	/**
	 * 所有的FeignClient都调用同一个MockMvcClient实例
	 * 
	 * @param applicationContext
	 * @return
	 */
	public static MockMvcClient getMockMvcClient(ApplicationContext applicationContext) {
		if (mockMvcClient == null) {
			mockMvcClient = new MockMvcClient(getMockMvc(applicationContext));
		}
		return mockMvcClient;
	}
}
