package cn.datax.common.dictionary.utils;

import cn.datax.common.redis.service.RedisService;
import cn.datax.common.utils.SpringContextHolder;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ConfigUtil {

    private ConfigUtil() {}

    private static volatile ConfigUtil instance;

    public static ConfigUtil getInstance() {
        if(instance == null) {
            synchronized (ConfigUtil.class) {
                if(instance == null) {
                    instance = new ConfigUtil();
                }
            }
        }
        return instance;
    }

    private RedisService redisService = SpringContextHolder.getBean(RedisService.class);

    /**
     * 获取参数
     * @param code
     */
    public Object getConfig(String code) {
        String key = "data:system:configs";
        Object object = redisService.get(key);
        if (null == object) {
            return null;
        }
        JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(object));
        Object o = jsonArray.stream().filter(obj -> ((JSONObject) obj).get("configKey").equals(code))
                .findFirst().orElse(null);
        return o;
    }
}
