import ukcrobots.core.Display;
import ukcrobots.simplecore.LightSensor;
import ukcrobots.simplecore.Motor;
import ukcrobots.util.Sleeper;

/**
 * A main method for the LightSearcher class.
 */
public class LightSearcherMain
{
    public static void main(String[] args)
    {
        LightSearcher searcher = new LightSearcher();
        searcher.run();
    }
}

/**
 * Search for the brightest light level in the vicinity.
 * The model rotates in position.
 * No attempt is made to orientate in the direction of
 * the brightest level.
 *
 * @author David J. Barnes
 * @version 2003.03.20
 */
class LightSearcher
{
    private Motor left, right;
    private LightSensor light;

    /**
     * Set up two motors to control the model, and one light
     * sensor to detect the brightest light source.
     */
    public LightSearcher()
    {
        left = new Motor('A');
        right = new Motor('C');
        light = new LightSensor(1);
    }

    /**
     * Have the model rotate in place, taking light readings
     * to discover the brightest value.
     * Display the brightest value on the Display at
     * the end of the run.
     */
    public void run()
    {
        // Use the motors at low power to try to avoid missing
        // a bright source.
        left.setPower(1);
        right.setPower(1);

        // Rotate in position.
        left.forward();
        right.flt();
        light.activate();

        // Find the brightest value over the course of
        // the given (arbitrary) number of readings.
        int brightest = findBrightest(10000);
        
        // Show the number.
        Display display = new Display();
        display.showNumber(brightest);

        // Turn everything off.
        left.stop();
        right.stop();
        light.passivate();

        // Pause before finishing.
        Sleeper sleeper = new Sleeper();
        sleeper.letTimePass(5000);
    }

    /**
     * Take a succession of readings and return the value
     * of the brightest reading found.
     * @param numberOfReadings How many readings to take.
     * @return The brightest light value found.
     *         A value in the range 0 ... 100
     */
    private int findBrightest(int numberOfReadings)
    {
        // Record the brightest reading.
        int brightest = -1;
        // Take a fixed number of readings.
        for(int i = 0; i < numberOfReadings; i++){
            int reading = light.readValue();
            if(reading > brightest){
                brightest = reading;
            }
        }
        return brightest;
    }
}

