package xtools.boot.cache.redis.monitor;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import jakarta.annotation.Resource;
import org.springframework.data.redis.connection.RedisCommands;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import xtools.core.StringUtils;

import java.util.Objects;
import java.util.Properties;

/**
 * <p>Title : RedisMonitor</p>
 * <p>Description : RedisMonitor</p>
 * <p>DevelopTools : Idea_x64_v2026.1</p>
 * <p>DevelopSystem : macOS Sequoia 15.7.5</p>
 * <p>Company : org.xujun</p>
 *
 * @author : XuJun
 * @version : 5.0.0
 * @date : 2026/01/01 09:30
 */
@Component
public class RedisMonitor {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 状态
     *
     * @return 状态数据
     */
    public JSONObject stats() {
        RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
        if (Objects.isNull(factory)) {
            return null;
        }
        // 获取redis命令
        RedisCommands commands = factory.getConnection().commands();
        // 获取相对应信息
        Properties info = commands.info();
        Object dbSize = commands.dbSize();
        Properties commandStats = commands.info("commandstats");
        JSONArray cmd = new JSONArray();
        if (Objects.nonNull(commandStats)) {
            commandStats.stringPropertyNames().forEach(key -> {
                String property = commandStats.getProperty(key);
                JSONObject data = JSONObject.of(
                        "name", StringUtils.removeStart(key, "cmdstat_"),
                        "value", StringUtils.substringBetween(property, "calls=", ",usec")
                );
                cmd.add(data);
            });
        }
        // 封装数据
        return JSONObject.of("info", info, "dbSize", dbSize, "cmd", cmd);
    }

}
