package com.hotent.assembly.mockmvc;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cloud.openfeign.FeignContext;

public class MockMvcContextBeanPostProcessor implements BeanPostProcessor {

	private final BeanFactory beanFactory;

	private MockMvcFeignObjectWrapper mockMvcFeignObjectWrapper;

	public MockMvcContextBeanPostProcessor(BeanFactory beanFactory) {
		this.beanFactory = beanFactory;
	}

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		if (bean instanceof FeignContext && !(bean instanceof MockMvcFeignContext)) {
			return new MockMvcFeignContext(getMockMvcFeignObjectWrapper(), (FeignContext) bean);
		}
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

	private MockMvcFeignObjectWrapper getMockMvcFeignObjectWrapper() {
		if (this.mockMvcFeignObjectWrapper == null) {
			this.mockMvcFeignObjectWrapper = this.beanFactory.getBean(MockMvcFeignObjectWrapper.class);
		}
		return this.mockMvcFeignObjectWrapper;
	}

}
