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

import br.ufrgs.inf.prosoft.adaptivecaching.cache.CacheInfo;
import br.ufrgs.inf.prosoft.adaptivecaching.cache.CacheMonitor;
import net.spy.memcached.MemcachedClient;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Map;

/**
 * The type Memcached monitor.
 */
public class MemcachedMonitor implements CacheMonitor {

    private MemcachedClient client;

    /**
     * Instantiates a new Memcached monitor.
     *
     * @throws IOException the io exception
     */
    public MemcachedMonitor() throws IOException {
        client = new MemcachedClient(new InetSocketAddress("localhost", 11211));
    }

    /**
     * @return
     * @see https://github.com/memcached/memcached/blob/master/doc/protocol.txt
     */
    @Override
    public CacheInfo getCacheInfo() {

        Map<SocketAddress, Map<String, String>> stats = client.getStats();

        CacheInfo cacheInfo = new CacheInfo();


        //TODO view if there are more than one socket
        for (SocketAddress socket : stats.keySet()) {
            cacheInfo.setTotalSpace(Long.valueOf(stats.get(socket).get("limit_maxbytes")));
            cacheInfo.setUsedSpace(Long.valueOf(stats.get(socket).get("bytes")));
            cacheInfo.setEvictedKeys(Long.valueOf(stats.get(socket).get("evictions")));
            cacheInfo.setKeyspaceHits(Long.valueOf(stats.get(socket).get("get_hits")));
            cacheInfo.setKeyspaceMisses(Long.valueOf(stats.get(socket).get("get_misses")));
            cacheInfo.setNumberOfObjects(Long.valueOf(stats.get(socket).get("curr_items")));
        }

        return cacheInfo;
    }
}
