/*
 * Email.java
 *
 * Created on May 19, 2004, 12:16 AM
 */
package spamfilter.email;
import java.io.*;
import java.util.Vector;
import java.util.TreeSet;
/**
 *
 * @author  Michael West
 */
public class Email {
    
    private Vector words = new Vector();
    private TreeSet wordsTree;
    private String fileName;
    

    
    //Constuctor to create Email object from text file located at "file"
    //i.e. "D:\\AI\\spamfilter\\ParsedEmails\\NoHtml1.txt"
    public Email(String file, StopList stopList) {
        fileName = file;
        String email = FileToString(fileName);
        
        String tempWords[] = email.toLowerCase().split("[ \n\t\r]");
        
        for(int indexTemp = 0; indexTemp < tempWords.length; indexTemp++) {
            String w = tempWords[indexTemp];
            if(w.length() > 2 && !stopList.constainsWord(w))
                words.add(w);
        }
        
        wordsTree = new TreeSet(words);
        
    }
    
    // returns true if word exists in email
    public boolean constainsWord(String word) {
        return wordsTree.contains(word);
    }
    
    //return a random word from the email
    public String getRandomWord() {       
        int num = (int)(Math.random() * words.size());
        
        return (String)words.get(num);
    }    
      
    
    //this method takes a file and returns it as a String object
    //it is only used withing the email class
    private static String FileToString(String fileName){
        try{
            FileReader filer = new FileReader(fileName);        
            StringBuffer contents = new StringBuffer();


            char cbuf[] = new char[256];

            int read = filer.read(cbuf);

            while(read !=-1) {
               contents.append(cbuf);
               read = filer.read(cbuf);
            }

            // close the file, otherwise waste memory
            filer.close();
            return new String(contents);   
        }catch(IOException e){}
            return null; //if file dosn't exist null is returned
    }    
    
    public String getFileName() { return fileName; };
    
}
