package apoc.systemdb;

import apoc.util.TestUtil;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.internal.helpers.collection.Iterables;
import org.neo4j.internal.helpers.collection.Iterators;
import org.neo4j.test.rule.DbmsRule;
import org.neo4j.test.rule.ImpermanentDbmsRule;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static org.junit.Assert.*;

public class SystemDbTest {

    @Rule
    public DbmsRule db = new ImpermanentDbmsRule();

    @Before
    public void setUp() throws Exception {
        TestUtil.registerProcedure(db, SystemDb.class);
    }

    @Test
    public void testGetGraph() throws Exception {
        TestUtil.testResult(db, "CALL apoc.systemdb.graph() YIELD nodes, relationships RETURN nodes, relationships", result -> {
            Map<String, Object> map = Iterators.single(result);
            List<Node> nodes = (List<Node>) map.get("nodes");
            List<Relationship> relationships = (List<Relationship>) map.get("relationships");

            assertEquals(2, nodes.size());
            assertTrue( nodes.stream().allMatch( node -> "Database".equals(Iterables.single(node.getLabels()).name())));
            List<String> names = nodes.stream().map(node -> (String)node.getProperty("name")).collect(Collectors.toList());
            assertThat( names, Matchers.containsInAnyOrder("neo4j", "system"));

            assertTrue(relationships.isEmpty());
        });
    }
}

@@ -323,24 +323,78 @@
 .Iterators;%0A
+import org.neo4j.internal.helpers.collection.MapUtil;%0A
 import org.n
@@ -1639,11 +1639,521 @@
 );%0A    %7D
+%0A%0A    @Test%0A    public void testExecute() %7B%0A        TestUtil.testResult(db, %22CALL apoc.systemdb.execute('SHOW DATABASES') YIELD row RETURN row%22, result -%3E %7B%0A            List%3CMap%3CString, Object%3E%3E rows = Iterators.asList(result.columnAs(%22row%22));%0A            assertThat(rows, Matchers.containsInAnyOrder(%0A                    MapUtil.map(%22name%22, %22system%22, %22default%22, false, %22status%22, %22online%22),%0A                    MapUtil.map(%22name%22, %22neo4j%22, %22default%22, true, %22status%22, %22online%22)%0A            ));%0A        %7D);%0A    %7D
 %0A%7D%0A

fix #1357: add `apoc.systemdb.execute`