/*
 * @topic T02225 Sorting Comparable Objects
 * @brief Another class Product2 that implements "sort by" feature
*/

package arraydemo;

public class Product2 implements Comparable {
    public final static int SORT_BY_PRICE = 0;
    public final static int SORT_BY_NAME = 1;
    static int sortBy = SORT_BY_PRICE;
    // Use
    //     Product2.setSortField( Product2.SORT_BY_PRICE );
    // or
    //     Product2.setSortField( Product2.SORT_BY_NAME );
    // to specify the desired sorting order.

    int code;
    String description;
    double price;

    // Constructors
    public Product2()
    {
        this.Product2( 1, "UNKNOWN", 1.0 );
    }

    public Product2( int cc, String dd, double pp )
    {
        code = cc;
        description = dd;
        price = pp;
        // Set default sorting order:
        setSortField(Product2.SORT_BY_PRICE);
    }

    // static operations
    public static void setSortField( int field ) {
        sortBy = field;
    }

    // getters and setters
    public String getName() {
        return description + " " + getPrice();
    }

    public double getPrice()
    {
        return price;
    }

    // operations
    public int compareTo(Object obj) {
        Product2 another = ( Product2 )obj;
        if ( sortBy == SORT_BY_PRICE ) {
            if (price < another.price) {
                return +1;
            } else if (price > another.price) {
                return -1;
            }
            return 0; // prices are equal
        } else if ( sortBy == SORT_BY_NAME ) {
            return -description.compareTo( another.description );
        }
        return 0;
    }

}//class Product2