package cn.qg.qaplatform.config;

import cn.qg.qaplatform.utils.HttpClientUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 启动时动态生成Namespace Map缓存
 */
@Slf4j
@Component
public class NamespaceCache {

    public static Map<String, String> namespaceMap = new HashMap<>();

    @PostConstruct
    public void init() {
        String url = "http://holmes.liangkebang.com/k8s/namespace/list?env=all";
        JSONObject response = HttpClientUtils.doGetReturnJson(url);
        JSONArray nsJsonArray = (JSONArray) response.get("data");
        List<Map> namespaceList = JSONArray.parseArray(nsJsonArray.toJSONString(), Map.class);
        for (Map map: namespaceList) {
            namespaceMap.put(map.get("name").toString(), map.get("mysqlHost") + ":" + map.get("mysqlPort"));
        }
        log.info("获取到Namespace列表：{}", JSON.toJSONString(namespaceMap));
    }

    /**
     * 获取namespace定时任务
     */
    @Scheduled(cron = "0 */30 * * * ?")
    public void getNsTask() {
        //每半个小时执行一次缓存
        init();
    }
}
