package trafficlight;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2002</p>
 * <p>Company: </p>
 * @author unascribed
 * @version 1.0
 */

public class TrafficLightModel
implements Runnable {

  private final static int GREEN = 2 ;
  private final static int YELLOW = 1 ;
  private final static int RED = 0  ;
  private final static int TIME_INTERVAL = 2000 ;

  int currentLight = GREEN ;
  ModelView mv ;
  Thread t ;

  void setModelView(ModelView mv) {
    this.mv = mv ;
  }

  void walk() {
System.out.println("entered: TrafficLightModel.walk") ;
     if ( t == null ) {
        t = new Thread(this) ;
        t.start();
     }
  }

  void setLight(int i) {
     currentLight = i ;
     mv.repaint() ;
  }

  int getLight() {
System.out.println("entered: TrafficLightModel.getLight returns "+ currentLight) ;
     return currentLight ;
  }

  void turnLight(int i) {
     setLight(i) ;
  }

  // implement Runnable

  public void run() {
     // the traffic light action
System.out.println("entered: run, sleeping ...") ;
     try {
        setLight(RED) ;
        t.sleep(TIME_INTERVAL) ;
        setLight(YELLOW) ;
        t.sleep(TIME_INTERVAL) ;
        setLight(GREEN) ;
        t.sleep(TIME_INTERVAL) ;
     } catch ( InterruptedException ie ) { }
System.out.println("exit: run") ;
     t = null ;
  }

}