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 9/10/2015
 */
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.addWord(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
	 *   @return true (since the word can always be added)
	 */
	public boolean addWord(String newWord) {
		this.words.add(newWord);
		return true;
	}
	
	/**
	 * Adds a word to the list (at the end), as long as it is not already stored.
	 *   @param newWord the word to be added
	 *   @return true if the word was added, false if already stored
	 */
	public boolean addWordNoDupes(String newWord) {
	    if (!this.findWord(newWord)) {
	        return this.addWord(newWord);
	    }
	    return false;
	}
	
	/**
	 * 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);
	}
	
	/**
	 * Determine the number of words stored in the dictionary list.
	 *   @return the number of words
	 */
	public int numWords() {
	    return this.words.size();
	}
	
	/**
	 * 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);
    	}
    }
}
