package cn.qg.qaplatform.config;

import cn.qg.qaplatform.utils.HttpClientUtils;
import cn.qg.qaplatform.utils.K8sService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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 {

    @Autowired
    K8sService k8sService;

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

    @PostConstruct
    public void init() {
        List<Map<String, String>> namespaceList = k8sService.getNamespaceList("all");
        for (Map<String, String> namespace: namespaceList) {
            namespaceMap.put(namespace.get("name"), namespace.get("mysqlHost") + ":" + namespace.get("mysqlPort"));
        }
        log.info("获取到Namespace列表：{}", JSON.toJSONString(namespaceMap));
    }

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