package com.hotent.assembly.mockmvc;

import java.util.HashMap;
import java.util.Map;

import org.springframework.cloud.openfeign.FeignContext;

import feign.Client;

public class MockMvcFeignContext extends FeignContext {
	private final MockMvcFeignObjectWrapper mockMvcFeignObjectWrapper;

	private final FeignContext delegate;

	public MockMvcFeignContext(MockMvcFeignObjectWrapper mockMvcFeignObjectWrapper, FeignContext delegate) {
		this.mockMvcFeignObjectWrapper = mockMvcFeignObjectWrapper;
		this.delegate = delegate;
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T getInstance(String name, Class<T> type) {
		T object = this.delegate.getInstance(name, type);
		if (object instanceof Client) {
			return object;
		}
		if (Client.class.getName().equals(type.getName()) && object == null) {
			Client client = new Client.Default(null, null);
			return (T) this.mockMvcFeignObjectWrapper.wrap(client);
		}
		return (T) this.mockMvcFeignObjectWrapper.wrap(object);
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> Map<String, T> getInstances(String name, Class<T> type) {
		Map<String, T> instances = this.delegate.getInstances(name, type);
		if (instances == null) {
			return null;
		}
		Map<String, T> convertedInstances = new HashMap<>();
		for (Map.Entry<String, T> entry : instances.entrySet()) {
			if (entry.getValue() instanceof Client) {
				convertedInstances.put(entry.getKey(), entry.getValue());
			} else {
				convertedInstances.put(entry.getKey(), (T) this.mockMvcFeignObjectWrapper.wrap(entry.getValue()));
			}
		}
		return convertedInstances;
	}

}
