1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * This library is free software; you can redistribute it and/or modify it under
5    * the terms of the GNU Lesser General Public License as published by the Free
6    * Software Foundation; either version 2.1 of the License, or (at your option)
7    * any later version.
8    *
9    * This library is distributed in the hope that it will be useful, but WITHOUT
10   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11   * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12   * details.
13   */
14  
15  package com.liferay.portlet.shopping.util.comparator;
16  
17  import com.liferay.portal.kernel.util.OrderByComparator;
18  import com.liferay.portlet.shopping.model.ShoppingItem;
19  
20  /**
21   * <a href="ItemPriceComparator.java.html"><b><i>View Source</i></b></a>
22   *
23   * @author Brian Wing Shun Chan
24   */
25  public class ItemPriceComparator extends OrderByComparator {
26  
27      public static String ORDER_BY_ASC = "categoryId ASC, price ASC, name ASC";
28  
29      public static String ORDER_BY_DESC =
30          "categoryId DESC, price DESC, name DESC";
31  
32      public static String[] ORDER_BY_FIELDS = {"categoryId", "price", "name"};
33  
34      public ItemPriceComparator() {
35          this(false);
36      }
37  
38      public ItemPriceComparator(boolean asc) {
39          _asc = asc;
40      }
41  
42      public int compare(Object obj1, Object obj2) {
43          ShoppingItem item1 = (ShoppingItem)obj1;
44          ShoppingItem item2 = (ShoppingItem)obj2;
45  
46          Long categoryId1 = new Long(item1.getCategoryId());
47          Long categoryId2 = new Long(item2.getCategoryId());
48  
49          int value = categoryId1.compareTo(categoryId2);
50  
51          if (value == 0) {
52              double price1 = (1 - item1.getDiscount()) * item1.getPrice();
53              double price2 = (1 - item2.getDiscount()) * item2.getPrice();
54  
55              if (price1 < price2) {
56                  value = -1;
57              }
58              else if (price1 > price2) {
59                  value = 1;
60              }
61          }
62  
63          if (value == 0) {
64              value = item1.getName().toLowerCase().compareTo(
65                  item2.getName().toLowerCase());
66          }
67  
68          if (_asc) {
69              return value;
70          }
71          else {
72              return -value;
73          }
74      }
75  
76      public String getOrderBy() {
77          if (_asc) {
78              return ORDER_BY_ASC;
79          }
80          else {
81              return ORDER_BY_DESC;
82          }
83      }
84  
85      public String[] getOrderByFields() {
86          return ORDER_BY_FIELDS;
87      }
88  
89      public boolean isAscending() {
90          return _asc;
91      }
92  
93      private boolean _asc;
94  
95  }