import java.util.*;

/*
 * InspectorThread - class that encapsulates the processing for
 * a thread that inspects request items.
 *
 * Author:  Mike Criscolo
 * Date:    09/02/97
 */

public class InspectorThread extends Thread {

    protected int            threadId;
    protected boolean        running;
    protected QueueObject    requestQ;
    protected QueueObject    responseQ;

    public InspectorThread(String name, int id, QueueObject response) {

        // Call the superclass
        super(name);

        // Store the thread id and response QueueObject
        threadId = id;
        responseQ = response;
        
        // Create the request QueueObject for the thread to use
        requestQ = new QueueObject("Thread " + threadId + " Queue");

        // Set the running boolean
        running = false;
    }

    // Set the running boolean to false and bump the main loop
    // off the wait.
    public void shutdown() {

        running = false;
        requestQ.BumpQueue();
    }

    // Main loop of the thread.
    public void run() {

        RequestObject thing;

        // Set running to true
        running = true;
        
        // While the thread is supposed to be running...
        while (running) {
            try {
                System.out.println("Thread " + threadId + ": waiting for items...");
                
                // Call the QueueObject's method to get a request
                thing = (RequestObject)requestQ.GetQueueItem();

                try {
                    // Sleep for time (convert to milliseconds)
                    sleep(thing.GetDelayTime()*1000);
                } catch (InterruptedException intExp) {
                    // No problem - try again
                }
                
                // Put some text in the request to show we handled it
                thing.SetResponseText("Inspected by #" + threadId);
                
                // Send it back
                responseQ.AddQueueItem(thing);
                
            } catch (NoSuchElementException e) {
                // Oh well, try again
            }
        }

        System.out.println("Thread " + threadId + " exiting!");
    }

    // Add a RequestObject to the thread's queue
    public void submitRequest(Object request) {
        
        requestQ.AddQueueItem(request);
    }
}