package org.commcare.data.xml;

import com.google.common.collect.ImmutableMap;

import org.javarosa.core.model.instance.ExternalDataInstance;
import org.javarosa.core.model.instance.TreeElement;
import org.javarosa.xml.util.InvalidStructureException;
import org.javarosa.xml.util.UnfullfilledRequirementsException;
import org.junit.Test;
import org.xmlpull.v1.XmlPullParserException;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import static org.junit.Assert.assertEquals;

public class VirtualInstancesTest {
    @Test
    public void testBuildSearchInputRoot()
            throws UnfullfilledRequirementsException, XmlPullParserException,
            InvalidStructureException, IOException {
        String instanceID = "search-input";
        ExternalDataInstance instance = VirtualInstances.buildSearchInputInstance(instanceID, ImmutableMap.of(
                "key0", "val0",
                "key1", "val1",
                "key2", "val2"
        ));
        String expectedXml = String.join(
                "",
                "<input id=\"search-input\">",
                "<field name=\"key0\">val0</field>",
                "<field name=\"key1\">val1</field>",
                "<field name=\"key2\">val2</field>",
                "</input>"
        );
        TreeElement expected = ExternalDataInstance.parseExternalTree(
                new ByteArrayInputStream(expectedXml.getBytes(StandardCharsets.UTF_8)),
                instanceID
        );
        assertEquals(expected, instance.getRoot());
    }
}

@@ -752,16 +752,48 @@
 ption %7B%0A
+        String ref = %22results%22;%0A
         
@@ -812,26 +812,59 @@
 nceI
-D = %22s
+d = VirtualInstances.makeS
 earch
--i
+I
 nput
-%22
+InstanceID(ref)
 ;%0A  
@@ -943,26 +943,19 @@
 nstance(
-instanceID
+ref
 , Immuta
@@ -1175,16 +1175,24 @@
 ch-input
+:results
 %5C%22%3E%22,%0A  
@@ -1570,17 +1570,17 @@
 nstanceI
-D
+d
 %0A       

fix instance test