package com.microservices.mon.k8s.domain.vo;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

@Data
public class CommonTypeVo {

    private String name;
    private String key;

    public static List<CommonTypeVo> eventReasonListToCommonTypeVoList(JSONObject eventReasonListQueryRes) {
        List<CommonTypeVo> commonTypeVoList = new ArrayList<>();
        if (eventReasonListQueryRes != null && eventReasonListQueryRes.getJSONObject("aggregations") != null
                && eventReasonListQueryRes.getJSONObject("aggregations").getJSONObject("distinct_reasons") != null
                && eventReasonListQueryRes.getJSONObject("aggregations").getJSONObject("distinct_reasons").getJSONArray("buckets") != null) {
            JSONArray eventReasonList = eventReasonListQueryRes.getJSONObject("aggregations").getJSONObject("distinct_reasons").getJSONArray("buckets");
            for (int i = 0; i < eventReasonList.size(); i++) {
                JSONObject eventReason = eventReasonList.getJSONObject(i);
                CommonTypeVo commonTypeVo = new CommonTypeVo();
                commonTypeVo.setName(eventReason.getString("key"));
                commonTypeVo.setKey(eventReason.getString("key"));
                commonTypeVoList.add(commonTypeVo);
            }
        }
        return commonTypeVoList;
    }

    public static List<CommonTypeVo> resourceObjectToCommonTypeVoList(List<PrometheusResultVo> resultList) {
        List<CommonTypeVo> commonTypeVoList = new ArrayList<>();
        for (PrometheusResultVo resultVo : resultList) {
            JSONObject metric = resultVo.getMetric();
            String nodeInstance = metric.getString("instance");
            String nodeIp = metric.getString("ip");
            CommonTypeVo commonTypeVo = new CommonTypeVo();
            commonTypeVo.setName(String.format("%s(%s)", nodeInstance, nodeIp));
            commonTypeVo.setKey(nodeIp);
            commonTypeVoList.add(commonTypeVo);
        }
        return commonTypeVoList;
    }
}
