package data;

/**
  * A collection of convenience {@link BasketEntryValue BasketEntryValues}.
  *
  * @author Steffen Zschaler
  * @version 2.0 18/08/1999
  * @since v2.0
  */
public final class BasketEntryValues {

  /**
    * A BasketEntryValue returning the value of a DataBasketEntry under the assumption that this describes a
    * StockItem movement. The value will be calculated by multiplying the number of items with the
    * default value of the associated CatalogItem.
    *
    * <p>To obtain the associated CatalogItem, the BasketEntryValue first tries to use the DataBasketEntries
    * destination and only if this is <code>null</code> it will try its source. If both are <code>null</code>
    * or if an exception occurs, the BasketEntryValue will return 0.</p>
    */
  public static final BasketEntryValue ONLY_STOCK_ITEMS = new BasketEntryValue()  {
    public Value getEntryValue (DataBasketEntry dbe) {
      Stock st = (Stock) dbe.getDestination();

      if (st == null) {
        st = (Stock) dbe.getSource();
      }

      if (st != null) {
        try {
          int nCount = ((dbe.getValue() instanceof Number)?
                        (((Number) dbe.getValue()).intValue()):
                        (1));

          return st.getCatalog (dbe.getOwner()).get (dbe.getSecondaryKey(), null, false).getValue().
                    multiply (nCount);
        }
        catch (Throwable t) {
          return new IntegerValue (0);
        }
      }
      else {
        return new IntegerValue (0);
      }
    }
  };

   /**
    * A BasketEntryValue returning the value of a DataBasketEntry under the assumption that this describes a
    * CatalogItem movement. The value will be taken from the CatalogItem's {@link CatalogItem#getValue} method.
    */
  public static final BasketEntryValue ONLY_CATALOG_ITEMS = new BasketEntryValue()  {
    public Value getEntryValue (DataBasketEntry dbe) {
      try {
        return ((CatalogItem) dbe.getValue()).getValue();
      }
      catch (Throwable t) {
        return new IntegerValue (0);
      }
    }
  };

  /**
    * A BasketEntryValue that returns 1 for each entry. You can use this BasketEntryValue to count entries that
    * match a given condition.
    */
  public static final BasketEntryValue COUNT_ITEMS = new BasketEntryValue() {
    private IntegerValue m_ivOne = new IntegerValue (1);

    public Value getEntryValue (DataBasketEntry dbe) {
      return m_ivOne;
    }
  };
}