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

import java.io.FileReader;

/**
 * Search through the collection of resistors for a pair
 * that provides a voltage divider with the requested ratio.
 *
 * @author Rod Byrne
 * @version 0.1
 * @since October 17, 2004
 */

public class VoltageDividerSearcher {
    private ResistorManager rManger;

    public VoltageDividerSearcher( ResistorManager rm ) {
        rManger = rm;
    }

    /**
     * search for a pair of resistors with division ratio k
     * that can vary +/- of the tolerance.
     */
    public List<VoltageDivider> search( double ratio, double tolerance ) {
        List<VoltageDivider> result = new ArrayList<VoltageDivider>();
        Iterator<Resistor> it = rManger.list();
        double from = ratio * ( 1.0 - tolerance );
        double to = ratio * ( 1.0 + tolerance );

        while ( it.hasNext() ) {
            Resistor r1 = it.next();
            double r1res = r1.getResistance();
            double r2resFrom = from*r1res/(1.0 - from);
            double r2resTo = to*r1res/(1.0 - to);
            Iterator<Resistor> r2It = rManger.select( r2resFrom, r2resTo );
            while ( r2It.hasNext() ) {
                Resistor r2 = r2It.next();
                result.add( new VoltageDivider( r1, r2 ) );
            }
        }
        return result;
    }

    /**
     * Provides the command line interface for the 
     * resistor searcher system.
     */
    public static void main( String[] args ) {
        String listFileName = null;
        double ratio = 1.0;
        double tolerance = 0.0;
        try {
            listFileName = args[0];
            ratio = Double.parseDouble( args[1] );
            tolerance = Double.parseDouble( args[2] );
        }
        catch ( Exception ex ) {
            System.err.println(
                "usage: java VoltageDividerSearcher file ratio tol" );
            System.exit( -1 );
        }

        try {
            FileReader rd = new FileReader( listFileName );
            ResistorManager rm = new ResistorManager( rd );
            rd.close();

            VoltageDividerSearcher searcher =
                new VoltageDividerSearcher( rm );
            List<VoltageDivider> result = searcher.search( ratio, tolerance );
            Iterator<VoltageDivider> it = result.iterator();
            while( it.hasNext() ) {
                System.out.println( it.next() );
            }
        }
        catch( Exception ex ) {
            System.err.println("ERROR processes the request!");
        }
    }
}
