package com.artfess.base.feign.impl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;

import feign.hystrix.FallbackFactory;

@SuppressWarnings("unchecked")
public abstract class AbstractFallbackFeignServiceFactory<T> implements FallbackFactory<T>{

	@Override
	public T create(Throwable cause) {
		Class<T> serviceInterface = getFeignServiceClass();
		FallbackFeignServiceHandler handler = new FallbackFeignServiceHandler(serviceInterface.getSimpleName(), cause);
		return generateProxy(serviceInterface, handler);
	}

	public Class<T> getFeignServiceClass() {
		return (Class<T>) ReflectionKit.getSuperClassGenericType(getClass(), 0);
	}

	private T generateProxy(Class<T> serviceInterface, InvocationHandler handler) {
		return (T) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { serviceInterface },
				handler);
	}
	
}
