/*______________________________________________________________________________
 * 
 * net.innig.util.OrderedType
 * 
 *______________________________________________________________________________
 * 
 * Copyright 2002 Paul Cantrell
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * (1) Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 * (2) Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in
 *     the documentation and/or other materials provided with the
 *     distribution. 
 *
 * (3) The name of the author may not be used to endorse or promote
 *     products derived from this software without specific prior
 *     written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *_______________________________________________________________________________
 */

package net.innig.util;

import java.util.*;

/**
    An enumerated type with a natural ordering.
    
    <p align="center">
    <table cellpadding=4 cellspacing=2 border=0 bgcolor="#338833" width="90%"><tr><td bgcolor="#EEEEEE">
        <b>Maturity:</b>
        This class is relatively new.  It looks great in unit testing,
        but hasn't seen real-world use yet.
    </td></tr><tr><td bgcolor="#EEEEEE">
        <b>Plans:</b>
        Perhaps add JDO support.
    </td></tr></table>
    
    @author Paul Cantrell
    @version [Development version]
*/
public abstract class OrderedType
    extends EnumeratedType
    implements Comparable
    {
    /** Returns the ordered set of valid types for the given enumerated type class.
     *  @throws IllegalArgumentException if the given class is not a subclass of OrderedType.
     */
    public static SortedSet/*<OrderedType>*/ allTypesSorted(Class orderedTypeClass)
        {
        checkOrdered(orderedTypeClass);
        return Collections.unmodifiableSortedSet(new TreeSet(allTypes(orderedTypeClass)));
        }
    
    /** Returns the set of valid type names for the given enumerated type class,
     *  in the type's (not the names') natural order.
     *  @throws IllegalArgumentException if the given class is not a subclass of OrderedType.
     */
    public static SortedSet/*<String>*/ allTypeNamesSorted(Class orderedTypeClass)
        {
        checkOrdered(orderedTypeClass);
        SortedSet result = new TreeSet(nameComparator(orderedTypeClass));
        result.addAll(allTypeNames(orderedTypeClass));
        return Collections.unmodifiableSortedSet(result);
        }
    
    /** Returns the comparator which gives the natural ordering on the given class.
     */
    public static Comparator comparator(final Class orderedTypeClass)
        {
        checkOrdered(orderedTypeClass);
        return new Comparator()
            {
            public int compare(Object o1, Object o2)
                {
                if(!orderedTypeClass.isInstance(o1))
                    throw new IllegalArgumentException(o1 + " is not an instance of " + orderedTypeClass);
                if(!orderedTypeClass.isInstance(o2))
                    throw new IllegalArgumentException(o2 + " is not an instance of " + orderedTypeClass);
                    
                return ((OrderedType) o1).compareTo((OrderedType) o2);
                }
            };
        }
    
    /** Returns a comparator which orders Strings by the natural ordering of their
     *  corresponding ordered types in the given class.
     */
    public static Comparator nameComparator(final Class orderedTypeClass)
        {
        checkOrdered(orderedTypeClass);
        return new Comparator()
            {
            public int compare(Object o1, Object o2)
                {
                OrderedType t1 = (OrderedType) resolveFromName(orderedTypeClass, (String) o1);
                OrderedType t2 = (OrderedType) resolveFromName(orderedTypeClass, (String) o2);
                return t1.compareTo(t2);
                }
            };
        }

    private static void checkOrdered(Class orderedTypeClass)
        {
        if(!OrderedType.class.isAssignableFrom(orderedTypeClass))
            throw new IllegalArgumentException(
                orderedTypeClass.getName() + " is not a subclass of " + OrderedType.class.getName());
        }
    
    private static Comparable nextNaturalOrder()
        {
        synchronized(naturalOrderSync)
            { return new Long(naturalOrder++); }
        }
    
    private static long naturalOrder = 0;
    private static final Object naturalOrderSync = new Object();
    
    //-----------------------------------------------------------------------------
    
    /** Creates a new enumerated type, ordered relative to its peers according to its lexical
     *  order in the source code.
     *  If any of the ordered types of a given class use this constructor, all must use it.
     */
    // We can get away with this because the JLS (S12.4.2) guarantees that static fields get
    // initialized in lexical order.  Kids, do not try this at home!  Oops...too late.
    public OrderedType(String name)
        { this(name, nextNaturalOrder()); }
    
    /** Creates a new enumerated type, ordered relative to its peers of the same class by an integer.
     *  If any of the ordered types of a given class use this constructor, all must use it.
     */
    public OrderedType(String name, int order)
        { this(name, new Integer(order)); }
    
    /** Creates a new enumerated type, ordered relative to its peers of the same class by a comparable object.
     *  The comparable object must be <b>immutable</b> and <b>mutually comparable</b> to the
     *  order objects assigned to other enumerated types of the same class.
     */
    public OrderedType(String name, Comparable order)
        {
        super(name);
        this.order = order;
        }
    
    public final int compareTo(Object that)
        {
        if(this.getClass() != that.getClass())
            throw new ClassCastException(
                "Unable to compare unmatching OrderedType classes: "
                + this.getClass().getName() + " != "
                + that.getClass().getName());
        return order.compareTo(((OrderedType) that).order);
        }
    
    public final boolean greaterThan(OrderedType that)
        { return this.compareTo(that) > 0; }
    
    public final boolean greaterThanEq(OrderedType that)
        { return this.compareTo(that) >= 0; }
    
    public final boolean lessThan(OrderedType that)
        { return this.compareTo(that) < 0; }
    
    public final boolean lessThanEq(OrderedType that)
        { return this.compareTo(that) <= 0; }
    
    /** Returns the comparable ordering object passed to the constructor.
     *  By default, this is not accessible to the outside world; subclasses may
     *  choose to expose it by exposing this as a public method.
     */
    protected Comparable getOrder()
        { return order; }
    
    private transient final Comparable order; // reestablished in super.readResolve()
    }





