package br.ufrgs.inf.prosoft.adaptivecaching.cache.vendors.redis;

import br.ufrgs.inf.prosoft.adaptivecaching.cache.CacheInfo;
import br.ufrgs.inf.prosoft.adaptivecaching.cache.CacheMonitor;
import redis.clients.jedis.Jedis;

/**
 * The type Redis monitor.
 */
public class RedisMonitor implements CacheMonitor {

    private Jedis jedis;

    /**
     * Instantiates a new Redis monitor.
     */
//TODO decouple this
    public RedisMonitor() {
        jedis = new Jedis("localhost");
    }

    /**
     * @return
     * @see http://redis.io/commands/INFO
     */
    @Override
    public CacheInfo getCacheInfo() {

        String info = jedis.info();

        CacheInfo cacheInfo = new CacheInfo();

        String maxmemory = getInfo(info, "maxmemory") == "0" ?
                getInfo(info, "maxmemory") :
                getInfo(info, "total_system_memory");

        cacheInfo.setTotalSpace(Long.valueOf(maxmemory));

        cacheInfo.setUsedSpace(Long.valueOf(getInfo(info, "used_memory")));
        cacheInfo.setEvictedKeys(Long.valueOf(getInfo(info, "evicted_keys")));
        cacheInfo.setKeyspaceHits(Long.valueOf(getInfo(info, "keyspace_hits")));
        cacheInfo.setKeyspaceMisses(Long.valueOf(getInfo(info, "keyspace_misses")));

        cacheInfo.setNumberOfObjects(jedis.dbSize());

        return cacheInfo;
    }

    private String getInfo(String info, String name) {
        String[] infos = info.split("\n");

        for (String namedInfo : infos) {
            if (namedInfo.indexOf(':') != -1 && namedInfo.substring(0, namedInfo.indexOf(':')).equals(name)) {
                info = namedInfo.substring(namedInfo.indexOf(':') + 1);
                break;
            }
        }

        return info.trim();
    }
}
