// Filename: Consumer.java
// Author: Professor Needham
// Course: SI411
// A modification of the Chapter 4 example in Silberschatz's OS text.

import java.util.*;
import java.io.*; // needed for file I/O

public class Consumer extends Thread {
   private BufferedWriter outFile;

   public Consumer(BoundedBuffer b) {
      buffer = b;
   }

   public void openFile(){
     try {
       outFile = new BufferedWriter(new FileWriter("consumer.txt"));
      } // end try
      catch (FileNotFoundException e) {
        System.out.println("File Not Found!");
        e.printStackTrace();
       }  // end catch
       catch (IOException e) {
         System.out.println("IO Problem!");
         e.printStackTrace();
       }  // end catch
   } // end openFile

   public void run()
   {
     String message;
     int total = 0; // how many dates written to file
     openFile();
     while (true)
      {
         int sleeptime = (int) (BoundedBuffer.NAP_TIME * Math.random() );

         System.out.println("Consumer sleeping for " + sleeptime + " seconds");

         try { sleep(sleeptime*1000); }
         catch(InterruptedException e) {}

         // consume an item from the buffer
         System.out.println("Consumer wants to consume.");

         message = (String)buffer.remove();
         if (total < 5){
           total++;
           try{
              outFile.write(message.toString());
              outFile.newLine();
              if (total == 5) {
                 System.out.println();
                 System.out.println("  ********* Wrote 5 dates to consumer.txt."
                                     + " Consumer Finished **********");
                 System.out.println();
                 outFile.close();
                 break;
              } // end if
           } // end try
           catch (IOException e) {
              System.out.println("IO Problem!");
              e.printStackTrace();
           }  // end catch
         } // end if
      }
   }

   private  BoundedBuffer buffer;
}



