import ukcrobots.core.BooleanSensorListener;
import ukcrobots.core.Motor;
import ukcrobots.core.SensorListener;
import ukcrobots.core.TouchSensor;

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

/**
 * An illustration of how to use a simple model with
 * motors attached to port A and port C. This model
 * has a TouchSensor attached. When touched, the model reverses
 * its direction. This code uses a sensor listener to identify when
 * the sensor has been touched.
 *
 * @author David J. Barnes (d.j.barnes@ukc.ac.uk)
 * @version 2003.03.03
 */
class BumperListener
{
    private Motor left, right;
    private TouchSensor touch;

    /**
     * Create two motors and a touch sensor, and set up the
     * touch sensor to listen for presses.
     */
    public BumperListener()
    {
        left = new Motor('A');
        right = new Motor('C');

        touch = new TouchSensor(2);

        // Add a listener for sensor presses.
        touch.addSensorListener(new BooleanSensorListener()
        {
            // Keep track of how many changes there have been, and
            // stop after 5.
            private int count = 0;

            /**
             * The sensor has either been pressed or released.
             * If pressed, reverse the motors.
             * @param oldState The previous state;
             *                 true == pressed, false == released.
             * @param currentState The current state;
             *                 true == pressed, false == released.
             */
            public void stateChanged(boolean oldState, boolean currentState)
            {
                if(currentState){
                    // A press.
                    if(count < 5){
                        left.reverse();
                        right.reverse();
                        count++;
                    }
                    else{
                        left.stop();
                        right.stop();
                        System.exit(0);
                    }
                }
                // else we are not interested in the release.
            }
        });
    }

    public void run()
    {
        // Activate the touch sensor so that its listener receives
        // notifications.
        touch.activate();
        left.forward();
        right.forward();

        // Now the listener takes over everything else ...
    }
}
