package com.railway.web.controller.monitor;

import com.railway.common.core.domain.AjaxResult;
import com.railway.common.utils.StringUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.springframework.data.redis.connection.RedisServerCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 缓存监控
 *
 * @author railway
 */
@RestController
@RequestMapping("/monitor/cache")
public class CacheController {

  private final RedisTemplate<String, String> redisTemplate;

  public CacheController(
      RedisTemplate<String, String> redisTemplate) {
    this.redisTemplate = redisTemplate;
  }

  @PreAuthorize("@ss.hasPermi('monitor:cache:list')")
  @GetMapping()
  public AjaxResult getInfo() {
    Properties info = (Properties) redisTemplate.execute(
        (RedisCallback<Object>) RedisServerCommands::info);
    Properties commandStats = (Properties) redisTemplate.execute(
        (RedisCallback<Object>) connection -> connection.info("commandstats"));
    Object dbSize = redisTemplate.execute(
        (RedisCallback<Object>) RedisServerCommands::dbSize);

    Map<String, Object> result = new HashMap<>(3);
    result.put("info", info);
    result.put("dbSize", dbSize);

    if(null != commandStats) {
      List<Map<String, String>> pieList = new ArrayList<>();
      commandStats.stringPropertyNames().forEach(key -> {
        Map<String, String> data = new HashMap<>(2);
        String property = commandStats.getProperty(key);
        data.put("name", StringUtils.removeStart(key, "cmdstat_"));
        data.put("value", StringUtils.substringBetween(property, "calls=", ",usec"));
        pieList.add(data);
      });
      result.put("commandStats", pieList);
    }
    return AjaxResult.success(result);
  }
}
