package com.sharefaith.thesharefaithapp.adapters;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;

/**
 * A memory-safe listing of K :V dictionary
 * Like a college student, this class forgets all data that probably won't be used soon.
 * (To prevent OutOfMemory error)
 * Otherwise it says nullllll
 *
 * Created by luke on 2/16/15.
 */
public class LimitedMapCache<K,V> {

    private Queue<K> queue;
    private HashMap<K,V> map;
	private int mMax;

    public LimitedMapCache(int limit)
    {
		this.mMax = limit;
        this.queue = new LinkedList<K>();
        this.map = new HashMap<K, V> ( this.mMax );
    }

    /**
     * Adds a new value to the MapCache.
     * @param key
     * @param value
     */
    public void add(K key, V value)
    {
        this.queue.add(key);
        this.map.put(key, value);

        if (this.queue.size() > this.mMax)
        {
            K removed = this.queue.remove();
            this.map.remove(removed);
        }
    }

    public V get(K key)
    {
        return this.map.get(key);
    }

	/**
	 * Called on lowmem or memory trim. This cache clears as it's unneeded.
	 */
	public void clear()
	{
		this.queue.clear();
		this.map.clear();
	}

}
