package com.elab.redis.componts.config.scope;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 缓存配置工厂
 * <p>
 * 使用前提 : 加载 {@link RedisConfigRefreshCallback#refresh()} 数据初始化源头
 *
 * @author liukaixiong
 * @Email liukx@elab-plus.com
 */
public class RedisConfigRefreshHelper {

    public static Map<String, String> configCache = new ConcurrentHashMap<>();

    private static RedisConfigRefreshHelper INSTANCE = new RedisConfigRefreshHelper();

    public static RedisConfigRefreshHelper getInstance() {
        return INSTANCE;
    }

    /**
     * 获取配置缓存信息
     *
     * @param key
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T get(String key, Class<T> clazz) {
        String body = configCache.get(key);

        if (StringUtils.isNotEmpty(body)) {
            return JSON.parseObject(body, clazz, Feature.AllowUnQuotedFieldNames, Feature.SupportAutoType);
        }

        return null;
    }

    public String get(String key) {
        return configCache.get(key);
    }

    /**
     * 刷新缓存配置
     * {@link com.elab.redis.componts.config.scope.RedisConfigRefreshCallback#refresh()}
     *
     * @param configMap
     */
    protected synchronized void refresh(Map<String, String> configMap) {
        configCache = configMap;
    }

}
