package com.elab.es.client.spring;

import com.elab.core.sql.ConfigurableFactory;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 具体代理dao类的工厂
 * <p>
 * 持有整个dao集合对象,每当方法调用会从工厂里面找指定的代理方法
 * </p>
 * <p>
 * 代理的缓存
 *
 * @author Liukx
 * @create 2018-01-03 11:30
 * @email liukx@elab-plus.com
 **/
public class ProxyCacheFactory<T> {

    private final Class<T> mapperInterface;
    private Map<Method, MethodCacheProxy> methodCache = new ConcurrentHashMap();

    public ProxyCacheFactory(Class<T> mapperInterface) {
        this.mapperInterface = mapperInterface;
    }

    public Class<T> getMapperInterface() {
        return this.mapperInterface;
    }

    public Map<Method, MethodCacheProxy> getMethodCache() {
        return this.methodCache;
    }

    protected T newInstance(MethodCacheProxy<T> mapperProxy) {
        return (T) Proxy.newProxyInstance(this.mapperInterface.getClassLoader(), new Class[]{this.mapperInterface}, mapperProxy);
    }

    public T newInstance(Object invokeBean, ConfigurableFactory configurableFactory) {
        MethodCacheProxy<T> mapperProxy = new MethodCacheProxy(invokeBean, this.mapperInterface, this.methodCache,
                configurableFactory);
        return this.newInstance(mapperProxy);
    }
}
