import java.util.*;
import java.io.*;

/**
 * AddressBook.java
 * 
 * Created: Sun Mar  2 18:04:33 2003
 *
 * @author <a href="mailto:shapiro@cse.buffalo.edu">Stuart C. Shapiro</a>
 */

public class AddressBook {
    private SortedList book;

    /**
     * Creates a new <code>AddressBook</code>, and loads it from the
     * file <code>emailList.txt</code>
     *
     */
    public AddressBook (){
	loadAddressBook();
    }
    
    /**
     * Loads this <code>AddressBook</code> from the file
     * <code>emailList.txt</code>.<br>
     * Abnormally terminates the program if the file is not found, or
     * if there is an error reading from it.
     */
    private void loadAddressBook() {
	book = new SortedList();
	BufferedReader reader = null;
	try {
	    /* Read all the elements from the file, emailList.txt,
	     * which is expected to have two lines per address:
	     * a person's name; the person's email address.
	     */
	    reader = new BufferedReader(new FileReader("emailList.txt"));
	    String input;
	    while ( (input = reader.readLine()) != null ) {
		book = book.insert(new AddressCard(input, reader.readLine()));
	    } // end of while ()
	    reader.close();
	} catch (FileNotFoundException e) {
	    System.out.println("emailList.txt not found.");
	    System.exit(1);
	} catch (IOException e) {
	    System.out.println("Error reading emailList.");
	    System.exit(1);
	}
    }

    /**
     * Writes this <code>AddressBook</code> into the file
     * <code>emailList.txt</code>.
     *
     */
    public void save () {
	PrintWriter writer;
	try {
	    writer = new PrintWriter(new FileOutputStream("emailList.txt"));
	    for (SortedList list = book; !list.isEmpty();
		 list = (SortedList)list.getRest()) {
		AddressCard card = (AddressCard)list.getFirst();
		writer.println(card.getName());
		writer.println(card.getAddress());
	    } // end of for
	    writer.flush();
	    writer.close();
	} catch (IOException e) {
	    System.out.println("ERROR writing emailList.txt");
	} // end of try-catch
    }

    /**
     * Returns a String representation of this <code>AddressBook</code>.
     *
     * @return a String representation of this <code>AddressBook</code>.
     */
    public String toString() {
	return book.toString();
    }

    /**
     * Sorts the Email Address Book file, <code>emailList.txt</code>.
     *
     * @param args a <code>String[]</code> value
     */
    public static void main (String[] args) {
	(new AddressBook()).save();
    } // end of main ()
    

}// AddressBook
