package ca.recrown.islandsurvivalcraft.caching;

import java.util.HashMap;
import java.util.PriorityQueue;

public class Cache <CacheValueType> {
    private final int maxCacheSize;
    private final HashMap<Identifier, CacheValue<CacheValueType>> dataCache;
    private final PriorityQueue<Identifier> ids;

    public Cache(int maxCacheSize) {
        dataCache = new HashMap<>(maxCacheSize);
        ids = new PriorityQueue<>(maxCacheSize);
        this.maxCacheSize = maxCacheSize;
    }

    public synchronized CacheValue<CacheValueType> retrieveCache(Identifier identifier) {        
        if (dataCache.containsKey(identifier)) {
            ids.remove(identifier);
            dataCache.get(identifier);
            CacheValue<CacheValueType> val = dataCache.get(identifier);
            val.getValue();
            ids.add(val.identifier);
            return dataCache.get(identifier);
        }
        if (ids.size() >= maxCacheSize) {
            dataCache.remove(ids.poll());
        }
        CacheValue<CacheValueType> value = new CacheValue<>(identifier);
        ids.add(identifier);
        dataCache.put(identifier, value);

        return value;
    }

    public void clearCache() {
        ids.clear();
        dataCache.clear();
    }
}