package com.huashe.park.common.animations.mybatis;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.ibatis.mapping.MappedStatement;

import com.huashe.common.annotation.mybatis.IgnoreTenant;

public class MethodMetadataCache {
    private static final Map<String, List<Method>> cache = new ConcurrentHashMap<>();

    public static List<Method> getAnnotatedMethods(MappedStatement mappedStatement) {

        return cache.computeIfAbsent(mappedStatement.getId(), key -> {
            try {
                String methodId = mappedStatement.getId();
                int lastDotIndex = methodId.lastIndexOf(".");
                String className = methodId.substring(0, lastDotIndex);
                Class<?> mapperClass = Class.forName(className);
                if (mapperClass.isAnnotationPresent(IgnoreTenant.class)) {
                    return Collections.emptyList();
                }
                List<Method> methods = new ArrayList<>();
                Arrays.stream(mapperClass.getMethods()).filter(f -> !f.isAnnotationPresent(IgnoreTenant.class))
                    .forEach(methods::add);
                return Collections.unmodifiableList(methods);
            }
            catch (ClassNotFoundException e) {
                return null;
            }
        });
    }
}
