package com.nuliji.tools.mybatis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tk.mybatis.mapper.MapperException;
import tk.mybatis.mapper.common.Mapper;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by gaojie on 2017/11/8.
 */
public class MapperHelper {
    protected static Map<Class<?>, Class<?>> entityClassMap = new ConcurrentHashMap<Class<?>, Class<?>>();
    private static final Logger logger = LoggerFactory.getLogger(MapperHelper.class);
    public static Class<?> getEntityClass(Mapper mapper){
        Class<?> mapperClass = mapper.getClass();
        if (entityClassMap.containsKey(mapperClass)) {
            return entityClassMap.get(mapperClass);
        } else {
            // spring代理
            Class<?> realClass = (Class)mapperClass.getGenericInterfaces()[0];
            Type[] types = realClass.getGenericInterfaces();
            for (Type type : types) {
                if (type instanceof ParameterizedType) {
                    ParameterizedType t = (ParameterizedType) type;
                    return (Class<?>) t.getActualTypeArguments()[0];
                }
            }
            throw new MapperException("无法获取 " + realClass.getName() + " 方法的泛型信息!");
        }
    }

    public static EntityTable getEntityTable(Mapper mapper){
        Class<?> entityClass = getEntityClass(mapper);
        return EntityHelper.getEntityTable(entityClass);
    }
}
