package cnrg.itx.ds;

/**
 * This class is used to hold returned record entries from the directory database
 */
public class ArrayRecords
{
	private Element m_head;
	private Element m_tail;
	private Element m_current;
	
	/**
	 * Default constructor
	 */
	public ArrayRecords(){
		m_head = null;
		m_tail = null;
		m_current = null;
	}
	
	/**
	 * Get the number of elements.  Zero implies empty list.
	 * @return number of elements
	 */
	public synchronized int count(){
		int count = 0;
		Element m_tmp = m_head;

		if (m_tmp == null)
			return count;

		count++;
		while (m_tmp != m_tail) {
			count++;
			m_tmp = m_tmp.getNext();
		}
		return count;
	}

	/**
	 * Reset to the first element position
	 */
	public synchronized void reset(){
		m_current = m_head;
	}

	/**
	 * Get the first element (also Reset to the first element position)
	 * @return the first element in the list
	 */
	public synchronized String first(){
		reset();
		if (m_current != null)
			return (String)m_current.getObject();

		return null;
	}

	/**
	 * Get the next element.  Returms NULL if call Next on the last element.
	 * NOTE: To traverse the list from the beginning, call first(), then calling next() to traverse to the end of the list
	 * @return the next element in the list
	 */
	public synchronized String next(){
		if (m_current != null && m_current != m_tail) {
			m_current = m_current.getNext();
			return (String)m_current.getObject();
		}

		return null;
	}

	/**
	 * Add a new element to the end of the list
	 * @param newValue the new element to be added to the list
	 */
	public synchronized void add(byte[] newValue){
		Element newElement = new Element();
		
		newElement.setObject(new String(newValue));
		
		if (m_head != null){
			m_tail.setNext(newElement);
			m_tail = m_tail.getNext();
		}
		else {
			m_head = newElement;
			m_tail = newElement;
		}
	}

	/**
	 * Add a new element to the end of the list
	 * @param newValue the new element to be added to the list
	 */
	public synchronized void add(String newValue){
		Element newElement = new Element();
		
		newElement.setObject(newValue);
		
		if (m_head != null){
			m_tail.setNext(newElement);
			m_tail = m_tail.getNext();
		}
		else {
			m_head = newElement;
			m_tail = newElement;
		}
	}
}
