import java.io.*;

/**
 * This class provides a file i/o capability to save
 * and load the AddressBook object.
 *
 * @author Dr. Caffeine
 */
class AddressBookStorage
{

//--------------------------------
//    Data Members
//--------------------------------
    
    /**
     * The name of the file where an AddressBook is stored
     */
   private String filename;
      
//--------------------------------
//    Constructors
//--------------------------------
    
    /**
     * Default constructor. 
     */
   public AddressBookStorage ( String filename )
   {
      setFile(filename);
   }
      
//-------------------------------------------------
//      Public Methods:
// 
//          AddressBook    read       (              )
//          void           setFile    (   String     )
//          void           write      ( AddressBook  )
//------------------------------------------------

    
    /**
     * Reads the address book from the designated file
     */
    public AddressBook read() throws IOException
    {
        AddressBook book;
  
        //first create an ObjectInputStream
        File inFile = new File(filename);
        FileInputStream inFileStream = 
                 new FileInputStream(inFile);
        ObjectInputStream inObjectStream = 
                 new ObjectInputStream(inFileStream);
  
        try {
           //read the data from it
           book = (AddressBook) inObjectStream.readObject();
        }
        catch (ClassNotFoundException e) {
           book = null;
           System.out.println("Error: AddressBook class not found");
        }
  
        //and close it
        inObjectStream.close();
  
        //and return the object
        return book;
    }
   
    
    /**
     * Sets the filename to the passed string.
     *
     * @param filename the name of the file to store
     *        an AddressBook object
     */
    public void setFile(String filename)
    {
        this.filename = filename;
        System.out.println("Inside setFile. Filename is " + filename); //TEMP
    }
   
   
    /**
     * Writes the address book to the designated file
     *
     * @param book the AddressBook to save to a file
     *
     */
    public void write(AddressBook book) throws IOException
    {
        //first create an ObjectOutputStream
        File outFile = new File(filename);
        FileOutputStream outFileStream = 
                 new FileOutputStream(outFile);
        ObjectOutputStream outObjectStream = 
                 new ObjectOutputStream(outFileStream);
  
        //save the data to it
        outObjectStream.writeObject(book);
  
        //and close it
        outObjectStream.close();
    }

    
            
}   