/* (non-Javadoc)
   * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
   */
  public int compare(InvoiceLineDTO perA, InvoiceLineDTO perB) {
    int retValue;

    // the line type should tell first
    if (perA.getOrderPosition() == perB.getOrderPosition()) {

      try {
        if (perA.getTypeId() == Constants.INVOICE_LINE_TYPE_SUB_ACCOUNT
            && perB.getTypeId() == Constants.INVOICE_LINE_TYPE_SUB_ACCOUNT) {
          // invoice lines have to be grouped by user
          // find out both users
          retValue = perA.getSourceUserId().compareTo(perB.getSourceUserId());
          /*
          Logger.getLogger(InvoiceLineComparator.class).debug(
                  "Testing two sub account lines. a.userid " +
                  perA.getSourceUserId() + " b.userid " + perB.getSourceUserId() +
                  " result " + retValue);
                  */
          if (retValue != 0) {
            // these are lines for two different users, so
            // they are different enough now
            return retValue;
          }
        }
        // use the number
        if (perA.getItem() != null && perB.getItem() != null) {
          ItemBL itemA = new ItemBL(perA.getItem());
          ItemBL itemB = new ItemBL(perB.getItem());
          if (itemA.getEntity().getNumber() == null && itemB.getEntity().getNumber() == null) {
            retValue =
                new Integer(perA.getItem().getId()).compareTo(new Integer(perB.getItem().getId()));
          } else if (itemA.getEntity().getNumber() == null) {
            retValue = 1;
          } else if (itemB.getEntity().getNumber() == null) {
            retValue = -1;
          } else {
            // none are null
            retValue = itemA.getEntity().getNumber().compareTo(itemB.getEntity().getNumber());
          }
        } else {
          retValue = 0;
        }
      } catch (Exception e) {
        Logger.getLogger(InvoiceLineComparator.class)
            .error("Comparing invoice lines " + perA + " " + perB, e);
        retValue = 0;
      }
    } else {
      retValue = new Integer(perA.getOrderPosition()).compareTo(perB.getOrderPosition());
    }
    /*
            Logger.getLogger(InvoiceLineComparator.class).debug(
                    "Comparing " + perA.getId() + " " + perB.getId() +
                    " result " + retValue);
    */
    return retValue;
  }