/* Copyright 2009 Palm, Inc.  All rights reserved. */

/**
 * Simple Object cache. Retains references to maxSize number
 * of objects, accessible by their keys. 
 * 
 * New items are pushed to the end of the queue (higher index) while old items
 * are picked off from the front of the queue (index 0)
 * The oldest objects are purged from the cache when the maxSize is reached. 
 * Each push or get from the cache updates the item's 'freshness'.
 * @param {Object} maxSize
 *
 */
function ObjCache(maxSize) {
	this.maxSize = maxSize;
	this.objQueue = new Array(); 
	this.dataStore = {};
};

ObjCache.prototype.updateItemQueue = function(id) {
	var index = this.objQueue.indexOf(id);
	if (index < 0 || index == this.objQueue.length - 1) {
		// item not in list, or already at end of queue
		return;
	}
	// pluck item from current position and push to end of queue
	this.objQueue.push(this.objQueue.splice(index, 1)[0]);
};

ObjCache.prototype.push = function(id, element) {
	if (!element) {
		return;
	}
	this.cleanCache(); // won't do anything if we have enough space
	if (!this.dataStore[id]) {
		this.objQueue.push(id);
	} else {
		this.updateItemQueue(id); 
	}
	// insert or update the element
	this.dataStore[id] = element;
};

ObjCache.prototype.get = function(id) {
	if (!this.dataStore[id]) {
		return undefined;
	}
	this.updateItemQueue(id);
	return this.dataStore[id];
};

ObjCache.prototype.isCached = function(id) {
	if (!this.dataStore[id]) {
		return false;
	}
	return true;
};

ObjCache.prototype.remove = function(id) {
	if (!this.dataStore[id]) {
		return undefined;
	}
	var toReturn = 	this.dataStore[id];
	delete this.dataStore[id]; // delete is the only way to get this out of the hash
	//Mojo.Log.info('removed item[%d]=%j, toReturn=%j', id, this.dataStore[id], toReturn);
	return toReturn;
};

ObjCache.prototype.cleanCache = function() {
	// try to keep the queue and cache from filling up too much. 
	while (this.objQueue.length > this.maxSize) {
			this.remove(this.objQueue.shift());
	}
};

ObjCache.prototype.getKeys = function() {
	return $H(this.dataStore).keys();
}


