/*
 *  Team 1
 *  CS575: Software Design
 *  Project Phase I
 *  Implicit Invocation style
 *  IIInput.java
 */

import java.io.*;
import java.util.Vector;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PipedReader;
import java.io.PipedWriter;

/**
 *  <p>Input class for the Implicit Invocation KWIC system.</p>
 *
 *  <p><b>PRE:</b> expects to receive the name(s) of the input file(s) and the 
 * SentenceCollection data object
 *  <br><b>POST:</b> after execution, all the files will have been parsed and 
 * data inserted into the SentenceCollection data object
 *
 *  @author Diana Tetelman
 */

public class IIInput extends IIMaster implements Runnable 
{
    private char tokenTermChar;
    private char lineTermChar;
    
    private boolean verboseFlag;
    
    private Vector files;
   
    private StreamTokenizer in;

    /**
     * Constructor
     * <p>Starts the thread with the name "Input Thread"</p>
     */
    public IIInput(Vector filenames, 
                   char tokenTerm, char lineTerm, 
                   boolean verbose)
    {
        files = filenames;
        tokenTermChar = tokenTerm;
        lineTermChar = lineTerm;        
        
        verboseFlag = verbose;
   
        new Thread(this, "Input Thread").start();
    }
    
    public void run()
    {
        for( int fIndex = 0; fIndex < files.size(); fIndex++ )
        {
            try{
                setupTokenizer((String)(files.elementAt(fIndex)));
                
                int tokenType = in.nextToken();
                while( tokenType != in.TT_EOF )
                {
                    Vector words = new Vector();                   
                    while( tokenType != in.TT_EOF && tokenType != in.TT_EOL && 
                           ! in.sval.toCharArray().equals(new Character(lineTermChar)) )
                    {
                        if( verboseFlag )
                            System.out.println("Adding the word \"" + in.sval + "\"");
                        
                        words.add(in.sval);                     
                        tokenType = in.nextToken();
                    }
                    inputCollection.addKWICRow(words.toArray());

                    // post message to the shifter with the index of the sentence
                    if( verboseFlag )
                        System.out.println("Sent message with " + (inputCollection.size()-1));
                    
                    shifterWriteMessagePipe.write(" " + Integer.toString(inputCollection.size()-1) + " ");
                                    
                    tokenType = in.nextToken();
                }   
                
                if( verboseFlag )
                {
                    // print the data collection
                    printCollection(inputCollection);
                }
            }
            catch(KWICException e)
            {
                if( verboseFlag )
                    e.printStackTrace();
                
                // !!! pass message to main with 
                // SendMessage(e);
            }            
            catch( FileNotFoundException e )
            {
                if( verboseFlag )
                    e.printStackTrace();
                
                // !!! pass message to main with 
                // SendMessage(new KWICException(files[fIndex] + " not found!")); 
            }
            catch( IOException e )
            {
                if( verboseFlag )
                    e.printStackTrace();
                
                // !!! pass message to main with 
                // SendMessage(new KWICException("Problem parsing file into tokens!"));
            }
        }
        // post message to shifter that no more input coming in
        try{ 
            shifterWriteMessagePipe.write(Integer.toString(-1));
            shifterWriteMessagePipe.close();
        }
        catch( Exception e ){ }
    }    
    

    /**
     * Sets up the file reader along with the tokenizer for the specified file
     *
     * @param   filename    String that contains the name of the file to be opened
     */
    private void setupTokenizer(String filename) throws KWICException
    {
        try{
            in = new StreamTokenizer(
                 new BufferedReader(
                 new FileReader(filename)));

            // if the newline is not the sentence terminator, treat it as whitespace
            if( lineTermChar == '\n' )
                in.eolIsSignificant(true);
            else
                in.eolIsSignificant(false);

            // set up the termination character if it is out of the current range.
            if( ! (Character.getNumericValue(tokenTermChar) >= '\u0000' && 
                   Character.getNumericValue(tokenTermChar) <= '\u0020') )
            {
                if( verboseFlag )
                    System.out.println("Setting the token termination char to \"" + 
                                    tokenTermChar + "\"");
                in.whitespaceChars(Character.getNumericValue(tokenTermChar),
                                   Character.getNumericValue(tokenTermChar));
            }
        }
        catch( FileNotFoundException e )
        {
            if( verboseFlag )
                e.printStackTrace();
            
            throw new KWICException(filename + " not found!");                
        }
    } 
}
