import java.io.*;
import java.util.*;

/**
 * A class that reads in the daily list of dispatching 
 * tasks from a file and hands them off to a Dispatcher
 *
 * Note: While this class' processDispatches()
 * method is executing, the application
 * will not be able to do anything else.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class DailyDispatchHandler extends AbstractDispatchHandler
{
    private long             currentTime, lastTime;

    /**
     * Construct a new DailyDispatchHandler
     *
     * @param d   The Dispatcher to use
     * @param f   The name of the dispatch file
     */
    public DailyDispatchHandler(Dispatcher d, String f) throws IOException
    {
        super(d, new BufferedReader(new FileReader(f)));
        lastTime = System.currentTimeMillis();
    }

    /**
     * Process an individual dispatch (required by 
     * AbstractDispatchHandler).
     *
     * @param line   The dispatch
     */
    public void processDispatch(String line)
    {
       int               wait;
       String            message;
       StringTokenizer   st;

       st = new StringTokenizer(line,"\t");
       wait = Integer.parseInt(st.nextToken());
       message = st.nextToken();
       
       // Wait until the appropriate time before dispatching
       while (System.currentTimeMillis()-lastTime < wait)
       {
           // Do nothing
       }
       
       dispatcher.dispatch(message);
       lastTime = System.currentTimeMillis();
    }
}
