/*
 * SortableProduct.java
 * Created on December 3, 2002
 */

package collections.sortable;

import java.util.Comparator;

/**
 * Demonstrates how to make a class sortable, by implementing
 * the Comparable interface to make the class comparable, and by
 * using the Comparator interface to create explicit comparators.
 * @author  Thomas Rowland
 */
public class SortableProduct implements Comparable {
  //explicit comparators
  public static final Comparator PRICE_COMPARATOR = new PriceComparator();
  public static final Comparator QTY_COMPARATOR = new QtyComparator();

  private int id;       // unique
  private String name;
  private String descr;
  private int qty;
  private double priceEa;
  private double priceNet;

  public SortableProduct(int _id, String _name,
                         String _descr, int _qty, double _price) {
    id = _id;
    name = _name;
    descr = _descr;
    qty = _qty;
    priceEa = _price;
    priceNet = qty * priceEa;
  }

  public int hashCode() {
    return id;
  }

  public boolean equals(Object o) {
    if (o != null && o.getClass().equals(this.getClass()))
      return (id == ((SortableProduct) o).getId());
    return false;
  }

  /**
   * Overridden method in the Comparator interface
   * makes the class comparable. Defines the Natural Ordering
   * and must be consistent with equals.
   */
  public int compareTo(Object o) {
    // throws a ClassCastException if not a SortableProduct object
    SortableProduct p = (SortableProduct) o;
    return new Integer(id).compareTo(new Integer(p.getId()));
  }
  public boolean isGreater(Object o) {
     SortableProduct p = (SortableProduct) o;   
    return id > p.getId();
  }

  public String toString() {
    return "\nid:" + id +
        "\nname=" + name +
        "\ndescr=" + descr +
        "\nqty=" + qty +
        "\npriceEach=" + priceEa +
        "\npriceNet=" + priceNet;
  }

  /**
   * Explicit comparator object to sort by price.
   */
  private static class PriceComparator implements Comparator {
    public int compare(Object o1, Object o2) {
      return (
          new Double(((SortableProduct) o1).getPriceEa()))
          .compareTo(
              new Double(((SortableProduct) o2).getPriceEa())
          );
    }
  }

  /**
   * Explicit comparator object to sort by quantity.
   */
  private static class QtyComparator implements Comparator {
    public int compare(Object o1, Object o2) {
      return (
          new Double(((SortableProduct) o1).getQty()))
          .compareTo(
              new Double(((SortableProduct) o2).getQty())
          );
    }
  }

  public int getId() {
    return id;
  }

  public String getName() {
    return name;
  }

  public String getDescr() {
    return descr;
  }

  public int getQty() {
    return qty;
  }

  public double getPriceEa() {
    return priceEa;
  }

  public double getPriceNet() {
    return priceNet;
  }
}