/**
 * Starter code for testing a parser for a Logo-like language;
 * used as part of an assignment in CIT594, Spring 2014.
 */
package starterCode;

import static org.junit.Assert.*;

import java.io.Reader;
import java.io.StringReader;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.junit.Before;
import org.junit.Test;

import tokenizer.Token;
import tokenizer.Tokenizer;
import tree.Tree;

/**
 * @author David Matuszek
 * @author // TODO fill in your name
 * @version February 2, 2014
 */
public class ParserTest {
    private Parser parser;
    private Set<String> keywords = new HashSet<String>();

    /**
     * @throws java.lang.Exception if an error occurs.
     */
    @Before
    public void setUp() throws Exception {
        // Nothing to do (yet)
    }    

    /**
     * Test method for {@link starterCode.Parser#Parser(java.lang.String)}.
     */
    @Test
    public void testParser() {
        // Not much to test here; mostly that the Parser constructor doesn't crash
        parser = new Parser("");
        parser = new Parser("2 + 2");
    }

    /**
     * Test method for {@link starterCode.Parser#isExpression()}.
     */
    @Test
    public void testIsExpression() {
        Tree<Token> expected;
        
        use("250");
        assertTrue(parser.isExpression());
        assertStackTop(tree("250"));
        
        use("hello");
        assertTrue(parser.isExpression());
        assertStackTop(tree("hello"));

        use("(xyz + 3)");
        assertTrue(parser.isExpression());
        assertStackTop(tree("+(xyz 3)"));

        use("a + b + c");
        assertTrue(parser.isExpression());
        assertStackTop(tree("+(+(a b) c)"));

        use("3 * 12 - 7");
        assertTrue(parser.isExpression());
        assertStackTop(tree("-(*(3 12) 7)"));

        use("12 * 5 - 3 * 4 / 6 + 8");
        assertTrue(parser.isExpression());
        expected = tree("+( -(*(12 5) /(*(3 4) 6)) 8)");
        assertStackTop(expected);
                     
        use("12 * ((5 - 3) * 4) / 6 + (8)");
        assertTrue(parser.isExpression());
        expected = tree("+(/(*(12 *(-(5 3) 4)) 6) 8)");
        assertStackTop(expected);
        
        use("");
        assertFalse(parser.isExpression());
        
        use("#");
        assertFalse(parser.isExpression());
    }

    /**
     * Test method for {@link starterCode.Parser#isExpression()}.
     */
    @Test(expected=RuntimeException.class)
    public void testIsBadExpression1() {
        use("17 +");
        parser.isExpression();
    }

    /**
     * Test method for {@link starterCode.Parser#isExpression()}.
     */
    @Test(expected=RuntimeException.class)
    public void testIsBadExpression2() {
        use("22 *");
        parser.isExpression();
    }

    /**
     * Test method for {@link starterCode.Parser#isTerm()}.
     */
    @Test
    public void testUnaryMinusBeforeFactor() {
        use("-a + b");
        assertTrue(parser.isExpression());
        assertStackTop(tree("+(-(a) b"));
        
        use("-a * b + c");
        assertTrue(parser.isExpression());
        assertStackTop(tree("+(*(-(a) b) c)"));
    }

    /**
     * Test method for {@link starterCode.Parser#isTerm()}.
     */
    @Test
    public void testUnaryMinusInsideParentheses() {
        use("(-foo + 3) / bar");
        assertTrue(parser.isExpression());
        assertStackTop(tree("/(+(-(foo) 3) bar)"));
    }

    /**
     * Test method for {@link starterCode.Parser#isUnsignedTerm()}.
     */
    @Test
    public void testIsUnsignedTerm() {        
        use("12");
        assertTrue(parser.isUnsignedTerm());
        assertStackTop(tree("12"));

        use("3*12");
        assertTrue(parser.isUnsignedTerm());
        assertStackTop(tree("*(3 12)"));

        use("u * v * z");
        assertTrue(parser.isUnsignedTerm());
        assertStackTop(tree("*(*(u v) z)"));
        
        use("20 * 3 / 4");
        assertTrue(parser.isUnsignedTerm());
        assertStackTop(tree("/(*(20 3) 4)"));

        use("20 * 3 / 4 + 5");
        assertTrue(parser.isUnsignedTerm());
        assertStackTop(tree("/(*(20 3) 4)"));
        unconsumedTokensShouldBe("+ 5");
        
        use("");
        assertFalse(parser.isUnsignedTerm());
        unconsumedTokensShouldBe("");
        
        use("#");
        assertFalse(parser.isUnsignedTerm());
        unconsumedTokensShouldBe("#");
    }

    /**
     * Test method for {@link starterCode.Parser#isTerm()}.
     */
    @Test
    public void testIsTerm() {
        use("3*12");
        assertTrue(parser.isTerm());
        assertStackTop(tree("*(3 12)"));

        use("-3*12");
        assertTrue(parser.isTerm());
        assertStackTop(tree("*(-(3) 12)"));
    }

    /**
     * Test method for {@link starterCode.Parser#isUnsignedFactor()}.
     */
    @Test
    public void testIsUnsignedFactor() {
        use("12");
        assertTrue(parser.isUnsignedFactor());
        assertStackTop(tree("12"));

        use("hello");
        assertTrue(parser.isUnsignedFactor());
        assertStackTop(tree("hello"));
        
        use("(xyz + 3)");
        assertTrue(parser.isUnsignedFactor());
        assertStackTop(tree("+(xyz 3)"));
        
        use("12 * 5");
        assertTrue(parser.isUnsignedFactor());
        assertStackTop(tree("12"));
        unconsumedTokensShouldBe("* 5");
        
        use("17 +");
        assertTrue(parser.isUnsignedFactor());
        assertStackTop(tree("17"));
        unconsumedTokensShouldBe("+");

        use("");
        assertFalse(parser.isUnsignedFactor());
        unconsumedTokensShouldBe("");
        
        use("getX");
        assertTrue(parser.isUnsignedFactor());
        assertStackTop(tree("getX"));
        
        use("getY");
        assertTrue(parser.isUnsignedFactor());
        assertStackTop(tree("getY"));
        
        use("#");
        assertFalse(parser.isUnsignedFactor());
        unconsumedTokensShouldBe("#");
    }

    /**
     * Test method for {@link starterCode.Parser#isUnsignedFactor()}.
     */
    @Test
    public void testIsFactor() {
        use("12");
        assertTrue(parser.isFactor());
        assertStackTop(tree("12"));

        use("hello");
        assertTrue(parser.isFactor());
        assertStackTop(tree("hello"));
        
        use("-12");
        assertTrue(parser.isFactor());
        assertStackTop(tree("-(12)"));

        use("-hello");
        assertTrue(parser.isFactor());
        assertStackTop(tree("-(hello)"));
    }

    /**
     * Test method for {@link starterCode.Parser#isAddOperator()}.
     */
    @Test
    public void testIsAddOperator() {
        use("+ - + $");
        assertTrue(parser.isAddOperator());
        assertStackTop(tree("+"));
        assertTrue(parser.isAddOperator());
        assertStackTop(tree("-"));
        assertTrue(parser.isAddOperator());
        assertFalse(parser.isAddOperator());
        unconsumedTokensShouldBe("$");
    }

    /**
     * Test method for {@link starterCode.Parser#isMultiplyOperator()}.
     */
    @Test
    public void testIsMultiplyOperator() {
        use("* / $");
        assertTrue(parser.isMultiplyOperator());
        assertTrue(parser.isMultiplyOperator());
        assertFalse(parser.isMultiplyOperator());
        unconsumedTokensShouldBe("$");
    }

    /**
     * Test method for {@link starterCode.Parser#isVariable()}.
     */
    @Test
    final public void testIsVariable() {
        use("hello   list abc123 header _");
        assertTrue(parser.isVariable());
        assertTrue(parser.isVariable());
        assertTrue(parser.isVariable());
        assertTrue(parser.isVariable());
        assertTrue(parser.isVariable());
    }

//  ----- "Helper" methods
    
    /**
     * The "isX" Parser methods try to recognize an X at the beginning
     * of the input, but should not consume tokens after the X. For example,
     * a factor may contain multiplications but not additions, so given a
     * string such as "3*x+5*y", the isFactor method should consume and
     * accept the "3*x" but leave the "+5*y" for later.
     * <p>
     * This method tests the input string to see whether the correct tokens
     * are left unconsumed. 
     * 
     * @param recognizer The Recognizer recently used to recognize some X from
     *        an input string.
     * @param expectedTokens The following Tokens that should remain in the input
     *        string after the X has been consumed. 
     */
    private void unconsumedTokensShouldBe(String expectedTokens) {
        Token expectedToken;
        Token actualToken;
        
        Tokenizer unconsumedTokens = parser.getTokenizer();
        Tokenizer expected =
                new Tokenizer(new StringReader(expectedTokens), keywords);

        try {
            while (expected.hasNext()) {
                expectedToken = expected.next();
                assertTrue(unconsumedTokens.hasNext());
                actualToken = unconsumedTokens.next();
                assertEquals(expectedToken, actualToken);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * Asserts that the parameter is equal to the top of the stack.
     * 
     * @param t The Tree to compare against the top of the stack.
     */
    private void assertStackTop(Tree<Token> t) {
        assertEquals(t, parser.stack.peek());
    }
    
    /**
     * Creates a Tree of Tokens from a String.
     * 
     * @param description The string representation of the Tree
     * (Note: Cannot include parentheses as values.)
     * 
     * @return A Tree of Tokens.
     */
    private Tree<Token> tree(String description) {
        Tree<String> treeOfStrings = Tree.parse(description);
        return convertToTreeOfTokens(treeOfStrings);
    }
    
    /**
     * Creates a Tree of Tokens from a Tree of Strings. The given
     * Tree of Strings is unchanged.
     * 
     * @param tree The tree to be translated.
     * @return The resultant tree of tokens.
     */
    private Tree<Token> convertToTreeOfTokens(Tree<String> tree) {
        Tree<Token> root = new Tree<Token>(makeOneToken(tree.getValue()));

        Iterator<Tree<String>> iter = tree.children();
        
        while (iter.hasNext()) {
            Tree<String> child = iter.next();
            root.addChildren(convertToTreeOfTokens(child));
        }
        return root;
    }
    
    /**
     * Returns a single token containing the given string.
     * 
     * @param word The thing to be turned into a Token.
     * @return The corresponding Token.
     */
    private Token makeOneToken(String word) {
        Tokenizer tokenizer = new Tokenizer(new StringReader(word), keywords);;
        return tokenizer.next();
    }

    /**
     * 
     * @param s The string to be parsed.
     */
    private void use(String s) {
        parser = new Parser(s);
    }
}
