package com.foreverwin.mesnac.console.mybatis.override;

import com.baomidou.mybatisplus.core.override.MybatisMapperMethod;
import org.apache.ibatis.session.SqlSession;

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

/**
 *
 * @description:
 * @author: syngna
 * @create: 2021-04-16 17:34
 */
public class ExtMybatisMapperProxyFactory<T> {

    private final Class<T> mapperInterface;

    private final Map<Method, MybatisMapperMethod> methodCache = new ConcurrentHashMap<>();

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

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

    public Map<Method, MybatisMapperMethod> getMethodCache() {
        return methodCache;
    }

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

    public T newInstance(SqlSession sqlSession) {
        final ExtMybatisMapperProxy<T> mapperProxy = new ExtMybatisMapperProxy(sqlSession, mapperInterface, methodCache);
        return newInstance(mapperProxy);
    }
}