import java.io.*;
import java.util.concurrent.*;


/**
 * A utility application that repeatedly saves a snapshot of the files in the
 * current directory.
 *
 * This version uses schules several DirectoryLister objects and waits for
 * them to complete. Also, this version can't be terminated.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 3
 */
public class AutoDir
{
    /**
     * The entry point of the application.
     *
     * args[0] contains the delay between snapshots.
     *
     * @param args The command-line arguments.
     */
    public static void main(String[] args) throws IOException
    {
        int         n;        
        long        delay;
        
        // Process the command-line arguments
        delay = 60000; // Every sixty seconds
        n     = 60;    // For an hour
        
        if ((args != null) && (args.length > 1))
        {
            delay = Long.parseLong(args[0]);
            n     = Integer.parseInt(args[1]);
        }
        
        // Create the ExecutorService
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        // Construct and schedule multiple DirectoryLister objects
        ScheduledFuture<Integer>[] result = new ScheduledFuture[n];
        for (int i=0; i<n; i++)
        {
            result[i] = scheduler.schedule(new DirectoryLister(), i*delay,
                                           TimeUnit.MILLISECONDS);
        }
        
        // Wait for and then print the number of files in the directory
        for (int i=0; i<result.length; i++)
        {
            try
            {
                System.out.printf("Number of Files: %d\n", 
                                  result[i].get().intValue());
            }
            catch (ExecutionException ie)
            {
                System.out.println("Number of Files: Unavailable\n");
            }
            catch (InterruptedException ie)
            {
                System.out.println("Number of Files: Unavailable\n");
            }
        }
        

        // Shutdown the ExecutorService
        scheduler.shutdownNow();
    }
}
