// Fig. 17.12: WriteRandomFile.java
// This program uses TextFields to get information from the
// user at the keyboard and writes the information to a
// random-access file.
import com.deitel.jhtp3.ch17.*;
import javax.swing.*;
import java.io.*;
import java.awt.event.*;
import java.awt.*;

public class WriteRandomFile extends JFrame {   
   private RandomAccessFile output;
   private BankUI userInterface;
   private JButton enter, open;
  
   // Constructor -- intialize the Frame 
   public WriteRandomFile()
   {
      super( "Write to random access file" );

      userInterface = new BankUI();
      enter = userInterface.getDoTask();
      enter.setText( "Enter" );
      enter.setEnabled( false );
      enter.addActionListener(
         new ActionListener() {
            public void actionPerformed( ActionEvent e )
            {
               addRecord();
            }
         }
      );

      addWindowListener(
         new WindowAdapter() {
            public void windowClosing( WindowEvent e )
            {
               if ( output != null ) {
                  addRecord();
                  closeFile();
               }
               else
                  System.exit( 0 );
            }
         }
      );
      open = userInterface.getDoTask2();

      open.setText( "Save As" );
      open.addActionListener(
         new ActionListener() {
            public void actionPerformed( ActionEvent e )
            {
               // Open the file
               openFile();
            }
         }      
      );
      getContentPane().add( userInterface,
                            BorderLayout.CENTER );

      setSize( 300, 150 );
      show();  
   }

   private void openFile()
   {
      JFileChooser fileChooser = new JFileChooser();

      fileChooser.setFileSelectionMode(
         JFileChooser.FILES_ONLY );
      int result = fileChooser.showSaveDialog( this );
     
      // user clicked Cancel button on dialog
      if ( result == JFileChooser.CANCEL_OPTION )
         return;

      File fileName = fileChooser.getSelectedFile();

      if ( fileName == null ||
           fileName.getName().equals( "" ) )
         JOptionPane.showMessageDialog( this,
            "Invalid File Name",
            "Invalid File Name",
            JOptionPane.ERROR_MESSAGE );
      else {
         // Open the file
         try {
            output = new RandomAccessFile( fileName, "rw" );
            enter.setEnabled( true );
            open.setEnabled( false );
         }
         catch ( IOException e ) {
            JOptionPane.showMessageDialog( this,
               "File does not exist",
               "Invalid File Name",
               JOptionPane.ERROR_MESSAGE );
         }      
      }
   }

   private void closeFile() 
   {
      try {
         output.close();
         System.exit( 0 );
      }
      catch( IOException ex ) {
         JOptionPane.showMessageDialog( this,
            "Error closing file",
            "Error", JOptionPane.ERROR_MESSAGE );
         System.exit( 1 );
      }
   }

   public void addRecord()
   {
      int accountNumber = 0;
      String fields[] = userInterface.getFieldValues();
      Record record = new Record();
      
      if ( !fields[ BankUI.ACCOUNT ].equals( "" ) ) {
         // output the values to the file
         try {
            accountNumber =
               Integer.parseInt( fields[ BankUI.ACCOUNT ] );

            if ( accountNumber > 0 && accountNumber <= 100 ) { 
               record.setAccount( accountNumber );
      
               record.setFirstName( fields[ BankUI.FIRST ] );
               record.setLastName( fields[ BankUI.LAST ] );                
               record.setBalance( Double.parseDouble(
                                  fields[ BankUI.BALANCE ] ) );

               output.seek( ( accountNumber - 1 ) *
                            Record.size() );
               record.write( output );
            }
            
            userInterface.clearFields();  // clear TextFields
         }
         catch ( NumberFormatException nfe ) {
                JOptionPane.showMessageDialog( this,
                   "Bad account number or balance",
                   "Invalid Number Format",
                   JOptionPane.ERROR_MESSAGE );
         }
         catch ( IOException io ) {
            closeFile();
         }
      }
   }
   
   // Create a WriteRandomFile object and start the program
   public static void main( String args[] )
   {
      new WriteRandomFile();
   }
}

/**************************************************************************
 * (C) Copyright 1999 by Deitel & Associates, Inc. and Prentice Hall.     *
 * All Rights Reserved.                                                   *
 *                                                                        *
 * DISCLAIMER: The authors and publisher of this book have used their     *
 * best efforts in preparing the book. These efforts include the          *
 * development, research, and testing of the theories and programs        *
 * to determine their effectiveness. The authors and publisher make       *
 * no warranty of any kind, expressed or implied, with regard to these    *
 * programs or to the documentation contained in these books. The authors *
 * and publisher shall not be liable in any event for incidental or       *
 * consequential damages in connection with, or arising out of, the       *
 * furnishing, performance, or use of these programs.                     *
 *************************************************************************/
 
