import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileWriter;

/**
 * Class that encapsulates a list of words.
 *   @author Dave Reed
 *   @version 8/15/13
 */
public class Dictionary {
	private ArrayList<String> words;

	/**
	 * Constructs an empty list of words.
	 */
	public Dictionary() {
		this.words = new ArrayList<String>();
	}

	/**
	 * Constructs a list of words that are read in from a file.
	 *   @param filename the file containing the words
	 */
	public Dictionary(String fileName) {
	    this.words = new ArrayList<String>();
	    
	    try {
	        Scanner infile = new Scanner(new File(fileName));
    	        while (infile.hasNext()) {
    	            String nextWord = infile.next();
    	            this.add(nextWord);
    	        }
    	        infile.close();
    	    }
    	    catch (java.io.FileNotFoundException e) {
    	        System.out.println("No such file: " + fileName);
    	    }
	}
	   
	/**
	 * Adds a word to the list (at the end).
	 *   @param newWord the word to be added
	 */
	public void add(String newWord) {
		this.words.add(newWord.toLowerCase());
	}

	/**
	 * Removes a word from the list.
	 *   @param word the word to be removed
	 *   @return true if the word was found and removed
	 */
	public boolean remove(String word) {
		return this.words.remove(word.toLowerCase());
	}
	
	/**
	 * Determines whether a word is stored in the list.
	 *   @param desiredWord the words to be searched for
	 *   @return true if that word is stored, else false
	 */
	public boolean findWord(String desiredWord) {
	    return this.words.contains(desiredWord.toLowerCase());
	}
	
	/**
	 * Determine the number of words stored in the dictionary list.
	 *   @return the number of words
	 */
	public int numWords() {
	    return this.words.size();
	}
	
	/**
	 * Displays the words in the list, one per line.
	 */
	public void display() {
	    for (int i = 0; i < this.words.size(); i++) {
	        System.out.println(this.words.get(i));
	    }
	}
	
	/**
	 * Saves the dictionary words to the specified file.
	 *   @param filename the name of the outputFile
	 */
	public void saveToFile(String filename) {
	    try {
	        FileWriter outfile = new FileWriter(new File(filename));
    	        for (String nextWord : this.words) {
    	            outfile.write(nextWord + "\n");
    	        }
    	        outfile.close();
    	    }
    	    catch (java.io.IOException e) {
    	        System.out.println("Unable to save to " + filename);
    	    }
	}   
}
