package net.ranides.assira.grammar;

import net.ranides.assira.io.ResourceUtils;
import net.ranides.assira.math.MathUtils;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

import static org.junit.Assert.*;

public class NodeTest {

    @Test
    public void findAll() throws IOException {
        G4Parser parser = G4Parser.builder().resource("Calculator.g4").build();

        G4Selector<Number> num1 = new G4SelectorBuilder<Number>()
            .withName("number")
            .mapRule("numberInt", node -> Integer.parseInt(node.text()))
            .mapRule("numberReal", node -> Double.parseDouble(node.text()))
            .prepare();

        G4Selector<Integer> pow1 = new G4SelectorBuilder<Integer>()
            .withName("pow")
            .mapRule("operatorPow", ctx -> {
                List<G4Node> args = ctx.findAll("../../expression").list();

                Number arg1 = num1.first(args.get(0));
                Number arg2 = num1.first(args.get(1));

                Number label1 = ctx.findAll("../../@a").first().map(num1::first).orElse(0);
                Number label2 = ctx.findAll("../../@b").first().map(num1::first).orElse(0);

                assertEquals(3, arg1.intValue());
                assertEquals(4, arg2.intValue());

                assertEquals(3, label1.intValue());
                assertEquals(4, label2.intValue());

                return MathUtils.pow(arg1.intValue(), arg2.intValue());
            })
            .prepare();

        int out = pow1.first(parser.parse("expression", "3^4"));
        assertEquals(81, out);
    }

}