// FileOpener.java

// Listener class used with window class ShapesWindow2,
// defined in ShapesWindow2.java

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

class FileOpener implements ActionListener
{
   // Window where the good data from the input file
   // will be displayed:
   private ShapesWindow2 window;

   // Where the good data from the file will be stored:
   private ShapeBoundedBuffer shapes;

   // Dialog box to display error messages
   // for bad input file data:
   private ErrorDialog errorsInFile = null;

   FileOpener(ShapesWindow2 window,
              ShapeBoundedBuffer shapes)
   {
      this.window = window;
      this.shapes = shapes;
   }  // constructor

   public void actionPerformed(ActionEvent e)
   {
      FileDialog fDialog = new FileDialog(window, "Input File");
      fDialog.setVisible(true);
      String filename = fDialog.getFile();
      if ( filename != null )
         open(filename);
   }  // method actionPerformed

   private void open(String filename)
   {
      TextFileInput in = new TextFileInput(filename);

      String line = in.readLine();
      while ( line != null )
      {
         try {
            shapes.add(ShapeOutline.parseShape(line));
         }  // try
         catch (ShapeTextFormatException stfe)  {
            if ( errorsInFile == null )  {
               errorsInFile = new ErrorDialog(window,
                                              "Errors in input data file");
               errorsInFile.printShortOneLineMessage("Bad shapes data");
            }  // if
            errorsInFile.println(stfe.getMessage());
         }  // catch
         catch (RuntimeException re)  {
            re.printStackTrace();
         }  // catch
         line = in.readLine();
      }  // while

      window.updateDisplay();
   }  // method open
}  // class FileOpener