package com.jay.monitor.data.server.ext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @Module TODO
 * @Description TODO
 * @Author liukaixiong
 * @Date 2020/12/16 11:01
 */
public interface ClazzEqualsProcess extends InitializingBean {

    Map<String, Map<Class, Method>> groupEqualsMap = new HashMap<>();

    Logger logger = LoggerFactory.getLogger(ClazzEqualsProcess.class);

    default Object apply(Object obj, Object... param) {
        String name = this.getClass().getSimpleName();
        String objectName = obj.getClass().getSimpleName();

        Map<Class, Method> nameSpaceMap = groupEqualsMap.get(name);
        if (nameSpaceMap != null) {
            Method method = nameSpaceMap.entrySet().stream().filter((clazz) -> {
                return clazz.getKey().isInstance(obj);
            }).findFirst().get().getValue();

            if (method != null) {
                try {
                    return method.invoke(obj, param);
                } catch (Exception e) {
                    logger.error("执行类匹配方法异常 : " + objectName + " -> " + method.getName(), e);
                }
            }
        }
        return null;
    }

    @Override
    default void afterPropertiesSet() throws Exception {
        String name = this.getClass().getName();
        Map<Class, Method> equalsMap = groupEqualsMap.get(name);

        if (equalsMap == null) {
            equalsMap = new HashMap<>();
            groupEqualsMap.put(name, equalsMap);
        }

        Map<Class, Method> finalEqualsMap = equalsMap;
        Arrays.stream(this.getClass().getMethods()).filter((method) -> {
            return method.getAnnotation(EqualsClassValue.class) != null;
        }).forEach((method) -> {
            Class value = method.getAnnotation(EqualsClassValue.class).value();
            finalEqualsMap.put(value, method);
        });
    }
}
