package com.elab.es.client.spring;

import com.elab.core.sql.ConfigurableFactory;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * 具体的jdk代理
 * <p>
 * JDK动态代理的具体实现类,这里会将具体的代理过程交给DaoMethod处理,该类只对做一次缓存
 * </p>
 *
 * 方法的缓存
 *
 * @author Liukx
 * @create 2018-01-03 11:31
 * @email liukx@elab-plus.com
 **/
public class MethodCacheProxy<T> implements InvocationHandler, Serializable {
    private static final long serialVersionUID = -6424540398559729838L;
    private final Object invokeBean;
    private final Class<T> mapperInterface;
    private final Map<Method, ProxyMethodInvoke> methodCache;
    private ConfigurableFactory configurableFactory;

    public MethodCacheProxy(Object invokeBean, Class<T> mapperInterface, Map<Method, ProxyMethodInvoke> methodCache, ConfigurableFactory configurableFactory) {
        this.invokeBean = invokeBean;
        this.mapperInterface = mapperInterface;
        this.methodCache = methodCache;
        this.configurableFactory = configurableFactory;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (Object.class.equals(method.getDeclaringClass())) {
            try {
                return method.invoke(this, args);
            } catch (Throwable var5) {
                throw new Exception(var5);
            }
        } else {
            ProxyMethodInvoke mapperMethod = this.cachedMapperMethod(method);
            return mapperMethod.execute(args);
        }
    }

    /**
     * 缓存DaoMethod对象
     *
     * @param method
     * @return
     */
    private ProxyMethodInvoke cachedMapperMethod(Method method) {
        ProxyMethodInvoke daoMethod = this.methodCache.get(method);
        if (daoMethod == null) {
            daoMethod = new ProxyMethodInvoke(this.mapperInterface, method, this.invokeBean, this.configurableFactory );
            this.methodCache.put(method, daoMethod);
        }
        return daoMethod;
    }
}
