package parser;

import java.io.*;

/**
 * Use the StreamTokenizer provided by in java.io to scan an input stream and extract an appropriate AToken.
 */
public class Tokenizer3 implements ITokenizer {
    /**
     * StreamTokenizer to use.
     */
    private StreamTokenizer _st;

    /**
     * Reader to use.
     */
    private Reader _fileReader;

    /**
     * Initialize _st to read from a input Reader file with the given input file name.
     *
     * @param inputFileName the name of the input text file
     * @throws FileNotFoundException
     */
    public Tokenizer3(String inputFileName) throws FileNotFoundException {
        // Create an input text file object:
        _fileReader = new FileReader(inputFileName);

        // Create a Streamtokenizer to parse the input text file:
        _st = new StreamTokenizer(_fileReader);

        _st.eolIsSignificant(false);

        // Where do we close the file? Java has no destructors!
        // DXN: close it in getNextToken() when the end-of-file is reached.
    }

    /**
     * Use _st to scan the input, extracts, and returns an appropriate concrete AToken.
     *
     * @return next token
     * @throws IllegalArgumentException Thrown if an illegal input is encountered.
     */
    public AToken getNextToken() {
        try {
            if (StreamTokenizer.TT_EOF != _st.nextToken()) {
                switch (_st.ttype) {
                    case '+':
                        {
                            System.err.println("Plus Token");
                            return PlusToken.Singleton;
                        }
                    case '*':
                        {
                            System.err.println("MUlt Token");
                            return MultToken.Singleton;
                        }
                    case StreamTokenizer.TT_NUMBER:
                        {
                            System.err.println("Num Token");
                            return new NumToken("" + _st.nval);
                        }
                    default:
                        throw new IllegalArgumentException("Illegal token!");
                }
            }
            else {
                _fileReader.close();
                System.err.println("EOF Token");
                return EOFToken.Singleton;
                //throw new IllegalStateException("Reading past EOF!");
            }
        }
        catch (IOException e) {
            System.out.println(e.getMessage());
            return null;
        }
    }

    /**
     * Put the previously consumed token back into the token stream. Can only put back one token.
     */
    public void putBack() {
        _st.pushBack();
    }
}
