package nxm.sys.lib;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

/** This class permits iteration over the elements of a collection in their
    natural order. <br>
    <br>
    This class replaces the <code>Util.SortedEnumeration</code> class.

    @author  J. Czechowski IV
    @since   NeXtMidas 1.9.0
 */
public class SortedIteration implements Enumeration<Object>, Iterator<Object> {
  /** The set of elements that are going to be returned by this Iterator. */
  private Object[] elements = null;

  /** The current index into the set of elements. */
  private int index = 0;

  /** Create a new instance that reads its values from the given enumeration.
      <br>
      <br>
      This is identical to
      <code>new&nbsp;SortedIteration(Collections.list(enumeration))</code>.

      @param enumeration The enumeration containing the data to be sorted into
                         this Enumeration.

      @see Collections#list(Enumeration)
   */
  public SortedIteration(Enumeration<?> enumeration) {
    this(Collections.list(enumeration));
  }

  /** Create a new instance that will use the values from the given collection.
      <br>
      <br>
      To prevent altering the existing Collection, a new Collection is created
      which includes all of the elements of the collection that is passed in,
      prior to sorting them. <br>
      <br>
      If it is desirable to sort the elements of a list "in place",
      consider using the {@link Collections#sort(List)} method.

      @param collection The collection containing the data to be sorted.

      @see Collections#sort(List)
   */
  public SortedIteration(Collection<?> collection) {
    this.elements = (new Vector<Object>(collection)).toArray();
    this.index    = 0;

    Arrays.sort(this.elements);
  }

  public boolean hasMoreElements() {
    return (this.index < this.elements.length);
  }

  public Object nextElement() {
    this.index++;
    return this.elements[this.index - 1];
  }

  public boolean hasNext() {
    return this.hasMoreElements();
  }

  public Object next() {
    return this.nextElement();
  }

  public void remove() {
    throw new UnsupportedOperationException(this.getClass().getName()
                                          + " does not support the removal of elements.");
  }
}
