package ru.yandex.wmconsole.data;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;

import ru.yandex.wmconsole.data.info.TreeInfo;

/**
 * User: baton
 * Date: 05.09.2007
 * Time: 21:57:31
 */
public class DBTreeInfoCache<K, V extends TreeInfo> {
    private final HashMap<K, V> cache = new HashMap<K, V>();
    private final LinkedList<K> queue = new LinkedList<K>();

    private static final int CACHE_SIZE = 100;

    public synchronized V search(K k, Date actualDate) {
        // get value from cache
        V res = cache.get(k);
        if (res == null) {
            // no value found
            return null;
        }

        // check that value in cache is up to date
        if ((res.getActualDate() != null) && (!res.getActualDate().before(actualDate))) {
            // cached entry is actual
            return res;
        } else {
            // cached entry is NOT actual
            cache.remove(k);
            return null;
        }
    }

    public synchronized void save(K k, V v) {
        // assure that K is not already in cache (maybe for another time)
        cache.remove(k);

        assureCacheSize();

        // add new value to cache
        cache.put(k, v);
        queue.addLast(k);
    }

    private void assureCacheSize() {
        if (cache.size() >= CACHE_SIZE) {
            K old = queue.removeFirst();
            cache.remove(old);
        }
    }
}
