/**
 * AI: Francisco Lara-Dammer 
 * A solution to Lab 13
*/


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

public class CarRace extends Applet
    implements Runnable {
   
    private Label outputs[];
    private final static int SIZE = 10;
    private int mileage[];
    private Thread threads[];
    
    public void init(){
	outputs = new Label[SIZE];
	
	threads = new Thread[SIZE];
	
	mileage = new int[SIZE];
	
	setLayout(new GridLayout(SIZE, 1, 5, 5));
	
	for (int i = 0; i < SIZE; ++i){
	    outputs[i] = new Label();
	    outputs[i].setBackground(Color.green);
	    add(outputs[i]); 
	    mileage[i] = 0;
	}
    }
    
    public void start(){
	
	for(int i = 0; i < threads.length; ++i){
	    threads[i] = new Thread(this, "Car " + (i+1));//create thread i
	    threads[i].start(); //start thread i
	}
    }
    
    public void run(){
	
	Thread currentThread = Thread.currentThread();
	int index = getIndex(currentThread);
	
	boolean noWinner =  true;//used to check if there is a winner or not.
	int i = 0;
	
	while (noWinner) {   
	    //sleep from 0 to 1 second
	    try{
		Thread.sleep((int)(Math.random()*1000));
	    }
	    catch(InterruptedException ie){
		System.err.println(currentThread.getName() + " with problem");
	    }
	
	    //increment the mileage in 1 unit to each car.
	    for(i = 0; i < SIZE; ++i){
		if(mileage[i] < 20){
		    if(getIndex(currentThread) == i){
			mileage[i]+= 1;
			outputs[index].
			setText(currentThread.getName() +
						  ": " + mileage[i] + " miles" );
		    }
		}
		else {
		    noWinner = false;
		    break;
		}
	    }
	  
	}

	//The winner box get red.
	outputs[i].setBackground(Color.red);
	
	//Prints a message in the system so that you can know that
	//your thread is over.
	System.err.println(currentThread.getName() + " terminating" );	
    }
    
    
    //Returns the index of a thread in the array of threads.
    private int getIndex(Thread thread){
	
	for(int i = 0; i < threads.length; ++i){
	    if(thread == threads[i])
		return i;
	}  
	    return -1; 
	
    }
}