/**
 * 
 */
package tree;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.richfaces.model.TreeRowKey;



/**
 * @author Nick Belaevski - nbelaevski@exadel.com
 * created 30.12.2006
 * 
 */
public class CachingTreeDataLocator {

	private static class CacheEntry {
		private int pid;
		private TreeRowKey key;
		private Object data;
	}
	
	private List cache = new ArrayList();
	private int number = 0;
	
	/* (non-Javadoc)
	 * @see com.exadel.jsf.model.preserve.TreeDataLocator#createData(java.lang.Object, com.exadel.jsf.model.TreeRowKey, com.exadel.jsf.model.TreeNode)
	 */
	public Object createData(Object locator, TreeRowKey rowKey) {
		for (Iterator iterator = cache.iterator(); iterator.hasNext();) {
			CacheEntry entry = (CacheEntry) iterator.next();
			if (entry.pid  == ((Integer) locator).intValue()) {
				return entry.data;
			}
		}
		
		return null;
	}

	/* (non-Javadoc)
	 * @see com.exadel.jsf.model.preserve.TreeDataLocator#createLocator(java.lang.Object, com.exadel.jsf.model.TreeRowKey, com.exadel.jsf.model.TreeNode)
	 */
	public Object createLocator(Object data, TreeRowKey rowKey) {
		for (Iterator iterator = cache.iterator(); iterator.hasNext();) {
			CacheEntry entry = (CacheEntry) iterator.next();

			if (entry.key.equals(rowKey)) {
				return Integer.valueOf(entry.pid);
			}
		}
		
		CacheEntry cacheEntry = new CacheEntry();
		cacheEntry.data = data;
		cacheEntry.key = rowKey;
		cacheEntry.pid = number++;
		
		cache.add(cacheEntry);
		
		return Integer.valueOf(cacheEntry.pid);
	}

}
