import java.awt.*;
import java.awt.event.*;

class CtlPanel extends Frame
  implements ActionListener, Runnable
{
  private Thread thread;

  Button stop;
  Button step;
  Button next_time;
  Button run;
  Button quit;

  int theState;

  static private int RUN = 0;
  static private int STOP = 1;
  static private int STEP = 2;
  static private int NEXT = 3;
  static private int QUIT = 4;

  public synchronized void setState(int state) {
    int oldstate = theState;

    System.out.println("setting state to "+state);
    if (oldstate == state)
      return;

    theState = state;

    if (oldstate == STOP)
      notify();
  }

  public synchronized int getState() {
    return theState;
  }

  // notice that we can call private methods from C
   public static void main(String[] args) {
     CtlPanel jc = new CtlPanel();
     jc.start();
  }	

  public static CtlPanel startGUI() {
    CtlPanel jc = new CtlPanel();
    jc.start();
    return jc;
  }


  // called from simulation to block until run/step is pressed
  public synchronized void waitRUN() {
    System.out.println("wait run");

    while (theState == STOP) {
      System.out.println("wait run...");
      try {
	wait();
      } catch (InterruptedException ex) {};
    }

    System.out.println("wait go");
  }

  CtlPanel() {
    super("Swarm Action");

    setLayout(new FlowLayout(FlowLayout.LEFT));

    run = new Button("Run");
    run.addActionListener(this);
    add(run);

    stop = new Button("Stop");
    stop.addActionListener(this);
    add(stop);

    step = new Button("Step");
    step.addActionListener(this);
    add(step);

    next_time = new Button("Next Time");
    next_time.addActionListener(this);
    add(next_time);

    quit = new Button("Quit");
    quit.addActionListener(this);
    add(quit);

    setVisible(true);
    setSize(100, 100);
    theState = RUN;
  }

  public void run() {
  }

  public void start() {
    System.out.println("starting GUI thread");

    if (thread == null) {
      thread = new Thread((Runnable)this);
      thread.start();
    }

  }

  //  stop:  close off your threads when you stop
  public void stop() {

    if (thread != null) {
      thread.stop();
    }

  }

  public void actionPerformed(ActionEvent event) {
    Object source = event.getSource();
    System.out.println("event!" + event);

    if (source == quit) {
      // all done...
      System.out.println("quit!");
      System.exit(0);
    } else if (source == step) {
      setState(STEP);
    } else if (source == run) {
      setState(RUN);
    } else if (source == stop) {
      setState(STOP);
    }
  }

}
