package io.wdd.rpc.scheduler.service.status;


import com.fasterxml.jackson.core.JsonProcessingException;
import io.wdd.common.utils.TimeUtils;
import io.wdd.rpc.status.beans.AgentMetric;
import io.wdd.rpc.status.service.SyncStatusService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Map;

import static io.wdd.common.config.OctopusObjectMapperConfig.OctopusObjectMapper;
import static io.wdd.rpc.status.AllAgentStatusCache.ALL_HEALTHY_AGENT_TOPIC_NAME_LIST;

/**
 * 定时任务 收集Agent的运行Metric的实际执行类
 */
//@Service
@Slf4j
public class AgentMetricStatusCollectService {


    @Resource
    SyncStatusService syncStatusService;

    @Resource
    RedisTemplate redisTemplate;

    /**
     * 收集所有健康主机的运行数据
     */
    public void collectHealthyAgentMetric() {

        // 检查是否存在健康的主机
        if (CollectionUtils.isEmpty(ALL_HEALTHY_AGENT_TOPIC_NAME_LIST)) {
            log.error("Metric Status Collect Failed ! no ALL_HEALTHY_AGENT_TOPIC_NAMES");
            return;
        }

        // 调用核心的服务
        Map<String, AgentMetric> agentMetricStatusMap = syncStatusService.SyncCollectAgentMetricStatus(
                ALL_HEALTHY_AGENT_TOPIC_NAME_LIST,
                10
        );

        // 2023年7月14日 使用redis存储状态数据
        log.info(
                "[Agent Metric] - 所有主机的状态为 => {}",
                agentMetricStatusMap
        );

        agentMetricStatusMap
                .entrySet()
                .stream()
                .forEach(
                        entry -> {

                            try {

                                String agentMetricString = OctopusObjectMapper.writeValueAsString(entry.getValue());

                                double currentTime = TimeUtils.utcTimeStampOfDouble();

                                redisTemplate
                                        .opsForZSet()
                                        .add(
                                                entry.getKey() + "-Metric",
                                                agentMetricString,
                                                currentTime
                                        );

                                // todo 处理长度缓存

                            } catch (JsonProcessingException e) {
                                throw new RuntimeException(e);
                            }


                        }
                );


    }

}
