package org.getopentest.actions;

import java.util.Map;
import java.util.function.Function;
import jdk.nashorn.api.scripting.AbstractJSObject;
import static org.testng.Assert.*;
import org.testng.annotations.Test;

public class ReadXmlNGTest {

    @Test
    public void testRootNodeText() {
        ReadXml readXml = new ReadXml();
        String xml = "<root attr1=\"value1\"><child1 attr1=\"value1\">child1 text</child1></root>";
        readXml.writeArgument("xml", xml);
        readXml.run();

        AbstractJSObject rootNode = (AbstractJSObject) readXml.readOutputValue("rootNode");

        assertEquals((String) rootNode.getMember("text"), "child1 text");
    }

    @Test
    public void testAttribute() {
        ReadXml readXml = new ReadXml();
        String xml = "<root attr1=\"value1\"><child1 attr1=\"value1\">child1 text</child1></root>";
        readXml.writeArgument("xml", xml);
        readXml.run();

        AbstractJSObject rootNode = (AbstractJSObject) readXml.readOutputValue("rootNode");

        String attr1 = ((Function<String, String>) rootNode.getMember("attribute")).apply("attr1");
        assertEquals(attr1, "value1");
    }
    
    @Test
    public void testAttributes() {
        ReadXml readXml = new ReadXml();
        String xml = "<root attr1=\"value1\"><child1 attr1=\"value1\">child1 text</child1></root>";
        readXml.writeArgument("xml", xml);
        readXml.run();

        AbstractJSObject rootNode = (AbstractJSObject) readXml.readOutputValue("rootNode");

        Object attrsObj = rootNode.getMember("attributes");
        if (attrsObj instanceof Map) {
            Map attrs = (Map)attrsObj;
            assertEquals(attrs.get("attr1"), "value1");
        }
    }

    @Test
    public void testElement() {
        ReadXml readXml = new ReadXml();
        String xml = "<root attr1=\"value1\"><child1 attr1=\"value1\">child1 text</child1></root>";
        readXml.writeArgument("xml", xml);
        readXml.run();

        AbstractJSObject rootNode = (AbstractJSObject) readXml.readOutputValue("rootNode");

        AbstractJSObject child1 = ((Function<String, AbstractJSObject>) rootNode.getMember("node")).apply("child1");
        assertEquals((String) child1.getMember("nodeType"), "element");
        assertEquals((String) child1.getMember("text"), "child1 text");
    }
}
