import java.util.TreeSet;
import java.util.SortedSet;
import java.util.Iterator;

import java.io.BufferedReader;
import java.io.Reader;
import java.io.IOException;
/**
 * ResistorManager maintain a collection of resistors.
 * Selected ranges of the resistors can be retrieved.
 *
 * @author Rod Byrne
 * @version 0.1
 * @since October 17, 2004
 */
public class ResistorManager {
    private SortedSet<Resistor> set = new TreeSet<Resistor>();

    /**
     * Create the list of resistors from rd.
     * Each line of the input source describes a resistor.
     * The resistance and power dissipation ability are
     * specified by a pair of double precision floating
     * point values.
     *
     */
    public ResistorManager( Reader rd )
        throws IOException
    {
        BufferedReader brd = new BufferedReader(rd);
        String line = null;
        /*
         * Convert each line into a resistor.
         */
        while ( (line=brd.readLine()) != null ) {
            String[] toks = line.split( "\\s+" );
            try {
                double ohms = Double.parseDouble( toks[0] );
                double watts = Double.parseDouble( toks[1] );
                Resistor r = new Resistor( ohms, watts );
                set.add( r );
            }
            catch( Exception ex ) {
                // ignore malformed line
            }
        }
    }

    /**
     * Return an iterator containing the resistors between
     * the from and to resistance values.
     */
    public Iterator<Resistor> select( double from, double to ) {
        Resistor r1 = new Resistor( from, 1.0 );
        Resistor r2 = new Resistor( to, 1.0 );
        return set.subSet( r1, r2 ).iterator();
    }

    /*
     * Return an iterator of the entire collection.
     */
    public Iterator<Resistor> list() {
        return set.iterator();
    }

    public double getSmallestResistance() {
        Resistor r = set.first();
        return r.getResistance();
    }

    public double getLargestResistance() {
        Resistor r = set.last();
        return r.getResistance();
    }
}
