package ec.gp.semantic.library;

import library.generator.TreeNode;
import library.space.SearchResult;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

final class Cache2 {
	private final static int MAX_SIZE = 1000;

	private final LinkedHashMap<Object, HashMap<Integer, List<SearchResult<TreeNode>>>> cache = new LinkedHashMap<Object, HashMap<Integer, List<SearchResult<TreeNode>>>>(MAX_SIZE, 0.75f, true) {
		@Override
		protected boolean removeEldestEntry(Map.Entry<Object, HashMap<Integer, List<SearchResult<TreeNode>>>> eldest) {
			return this.size() > MAX_SIZE;
		}
	};

	public List<SearchResult<TreeNode>> get(final Object query, final Integer maxHeight) {
		HashMap<Integer, List<SearchResult<TreeNode>>> entry = this.cache.get(query);

		if (entry != null) {
			return entry.get(maxHeight);
		}

		return null;
	}

	public void set(final Object query, final List<SearchResult<TreeNode>> result, final Integer maxHeight) {
		assert query != null;

		HashMap<Integer, List<SearchResult<TreeNode>>> entry = this.cache.get(query);

		if (entry == null) {
			entry = new HashMap<Integer, List<SearchResult<TreeNode>>>();
			this.cache.put(query, entry);
		}

		entry.put(maxHeight, result);
	}
}
