/**
 * 
 */
package gov.va.med.cds.persistence.hibernate.common;

import java.io.Serializable;
import java.util.List;

import org.dom4j.Element;
import org.hibernate.HibernateException;
import org.hibernate.collection.internal.PersistentElementHolder;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.persister.collection.CollectionPersister;

/**
 * @author vhaislegberb
 *
 */
public class ListIndexablePersistentElementHolder extends
		PersistentElementHolder {

	private static final long serialVersionUID = 9090878174085539836L;

	public ListIndexablePersistentElementHolder(SessionImplementor session,
			CollectionPersister persister, Serializable key)
			throws HibernateException {
		super(session, persister, key);
	}

	public ListIndexablePersistentElementHolder(SessionImplementor session,
			Element element) {
		super(session, element);
	}
	
	public Object getIndex(Object entry, int i, CollectionPersister persister) {
		if(entry instanceof String)
		{
			// matches the first child element string value and returns the Integer index of the value.
			String elementText = ((String)entry).trim();
			
			List<Element> children = (List<Element>)this.element.elements();
			for(int x = 0; x < children.size(); x++)
			{
				if(elementText.equals(children.get(x).getTextTrim()))
				{
					return new Integer(i);
				}
			}
			
			return null;
		}
		
		return super.getIndex(entry, i, persister);
	}

}
