]> gitweb.fperrin.net Git - GpsPrune.git/blob - tim/prune/data/sort/WaypointComparer.java
Version 17, September 2014
[GpsPrune.git] / tim / prune / data / sort / WaypointComparer.java
1 package tim.prune.data.sort;
2
3 import java.util.Comparator;
4
5 import tim.prune.data.DataPoint;
6
7
8 /**
9  * Class for comparing waypoints to sort them by name or timestamp
10  */
11 public class WaypointComparer implements Comparator<DataPoint>
12 {
13         /** Sort mode */
14         private SortMode _sortMode;
15
16
17         /**
18          * Constructor
19          * @param inMode sort mode
20          */
21         public WaypointComparer(SortMode inMode)
22         {
23                 _sortMode = inMode;
24         }
25
26         /**
27          * Main compare method
28          */
29         public int compare(DataPoint inP1, DataPoint inP2)
30         {
31                 if (inP2 == null || !inP2.isWaypoint()) return -1; // all nulls at end
32                 if (inP1 == null || !inP1.isWaypoint()) return 1;
33
34                 // Sort by time, if requested
35                 int result = 0;
36                 if (_sortMode == SortMode.SORTBY_TIME) {
37                         result = compareTimes(inP1, inP2);
38                 }
39                 // check names if names requested or if times didn't work
40                 if (result == 0) {
41                         result = inP1.getWaypointName().compareTo(inP2.getWaypointName());
42                 }
43                 // names and times equal, try longitude
44                 if (result == 0) {
45                         result = inP1.getLongitude().getDouble() > inP2.getLongitude().getDouble() ? 1 : -1;
46                 }
47                 // and latitude
48                 if (result == 0) {
49                         result = inP1.getLatitude().getDouble() > inP2.getLatitude().getDouble() ? 1 : -1;
50                 }
51                 return result;
52         }
53
54         /**
55          * Compare the timestamps of the two waypoints
56          * @param inP1 first point
57          * @param inP2 second point
58          * @return compare value (-1,0,1)
59          */
60         private int compareTimes(DataPoint inP1, DataPoint inP2)
61         {
62                 // Points might not have timestamps
63                 if (inP1.hasTimestamp() && !inP2.hasTimestamp()) return 1;
64                 if (!inP1.hasTimestamp() && inP2.hasTimestamp()) return -1;
65                 if (inP1.hasTimestamp() && inP2.hasTimestamp())
66                 {
67                         // Compare the timestamps
68                         long secDiff = inP1.getTimestamp().getMillisecondsSince(inP2.getTimestamp());
69                         return (secDiff<0?-1:(secDiff==0?0:1));
70                 }
71                 // neither has a timestamp
72                 return 0;
73         }
74 }