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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

/**
 * 分组工厂
 *
 * @author liukaixiong
 * @Email liukx@elab-plus.com
 * @date 2021/9/7 - 10:18
 */
public class GroupFactory {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private static GroupFactory INSTANCE = new GroupFactory();

    public static GroupFactory getINSTANCE() {
        return INSTANCE;
    }

    private Map<String, Object> groupMap = new ConcurrentHashMap<>();

    public void registerObject(String prefix, List<?> beanList, Function<Object, String> group) throws Exception {
        for (Object bean : beanList) {
            String name = group.apply(bean);

            if (StringUtils.isEmpty(name)) {
                continue;
            }

            String key = generateKey(prefix, name);
            Object oldBean = groupMap.put(key, bean);

            if (oldBean != null) {
                logger.warn(" GroupFactory value 存在重复 : " + key + " bean : " + bean + " 被覆盖!");
            }

        }
    }

    private String generateKey(String prefix, String name) {
        String key = prefix + "-" + name;
        return key;
    }

    public <T> T getObject(String prefix, String name, Class<T> clazz) {
        return (T)groupMap.get(prefix + "-" + name);
    }

    private String process(Object call) {

        if (call instanceof Enum) {
            return ((Enum<?>)call).name();
        }

        return null;
    }

}
