package cgeo.geocaching.sorting;

import cgeo.geocaching.Geocache;
import cgeo.geocaching.geopoint.Geopoint;

import java.util.List;

/**
 * sorts caches by distance to given position
 *
 */
public class DistanceComparator extends AbstractCacheComparator {

    final private Geopoint coords;
    final private List<Geocache> list;
    private boolean cachedDistances;

    public DistanceComparator(final Geopoint coords, List<Geocache> list) {
        this.coords = coords;
        this.list = list;
    }

    /**
     * calculate all distances only once to avoid costly re-calculation of the same distance during sorting
     */
    private void calculateAllDistances() {
        if (cachedDistances) {
            return;
        }
        for (final Geocache cache : list) {
            if (cache.getCoords() != null) {
                cache.setDistance(coords.distanceTo(cache.getCoords()));
            }
        }
        cachedDistances = true;
    }

    @Override
    protected boolean canCompare(Geocache cache1, Geocache cache2) {
        return true;
    }

    @Override
    protected int compareCaches(final Geocache cache1, final Geocache cache2) {
        calculateAllDistances();
        if (cache1.getCoords() == null && cache2.getCoords() == null) {
            return 0;
        }
        if (cache1.getCoords() == null) {
            return 1;
        }
        if (cache2.getCoords() == null) {
            return -1;
        }
        return Float.compare(cache1.getDistance(), cache2.getDistance());
    }

}

@@ -1205,324 +1205,271 @@
     
-if (cache1.getCoords() == null &&
+final Float distance1 =
  cache
-2
+1
 .get
-Coords() == null) %7B%0A            return 0;%0A        %7D%0A        if (cache1.getCoords() == null) %7B%0A            return 1;%0A        %7D%0A        if (cache2.getCoords() == null) %7B%0A            return -1;%0A        %7D%0A        return Float.compare(cache1.getDistance(), cache2.getD
+Distance();%0A        final Float distance2 = cache2.getDistance();%0A        if (distance1 == null) %7B%0A            return distance2 == null ? 0 : 1;%0A        %7D%0A        return distance2 == null ? -1 : Float.compare(distance1, d
 istance
-()
+2
 );%0A 

make the distance comparator work with approximate distance