/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package usda.weru.weps.location;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import javax.measure.Measurable;
import javax.measure.quantity.Length;
import javax.measure.unit.SI;
import org.jscience.geography.coordinates.LatLong;
import usda.weru.gis.GISUtil;

/**
 * Compares Stations based on their distance from a given LatLong.
 * @author Joseph Levin <joelevin@weru.ksu.edu>
 */
public class StationDistanceComparator implements Comparator<Station>{

    private final LatLong c_from;
    private final Map <Station, Double> c_distanceCache;

    /**
     * 
     * @param from
     */
    public StationDistanceComparator(LatLong from){
        c_from = from;
        c_distanceCache = new HashMap<Station, Double>();
    }

	/**
	 *
	 * @param station1
	 * @param station2
	 * @return
	 */
	@Override
    public int compare(Station station1, Station station2) {
        double distance1 = getCachedDistance(station1);
        double distance2 = getCachedDistance(station2);

        if(distance1 < distance2){
            return -1;
        }
        else if (distance1 > distance2){
            return 1;
        }
        else {
            return 0;
        }
    }

    private double getCachedDistance(Station station){
        if(station == null){
            return Double.NaN;
        }
        Double distanceMeters = c_distanceCache.get(station);

        if(distanceMeters == null){

            Measurable<Length> distance = GISUtil.distanceBetweenCoordinates(c_from, station.getLatLong());
            distanceMeters = distance != null ? distance.doubleValue(SI.KILOMETER) : Double.NaN;
            c_distanceCache.put(station, distanceMeters);
            //System.out.println( Double.toString(distance) + " : " + station.toString() );
        }
        return distanceMeters;

    }


}
