package ee.shy.core.diff;

import ee.shy.core.Tree;
import ee.shy.storage.DataStorage;
import ee.shy.storage.MapStorage;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.FromDataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;

import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assume.assumeNotNull;

@RunWith(Theories.class)
public class TreeDifferTest {
    private DataStorage storage;
    private TreeDiffer treeDiffer;

    @DataPoints("trees")
    public static String[] listTrees() throws URISyntaxException, IOException {
        return Files.list(getResourcePath("")).map(path -> path.getFileName().toString()).toArray(String[]::new);
    }

    @Before
    public void setUp() throws Exception {
        storage = new MapStorage();
        treeDiffer = new TreeDiffer(storage);
    }

    @Theory
    public void testDiff(
            @FromDataPoints("trees") String original,
            @FromDataPoints("trees") String revised
    ) throws Exception {
        InputStream expectedStream = getClass().getResourceAsStream(original + "-" + revised);
        assumeNotNull(expectedStream);
        List<String> expectedLines = IOUtils.readLines(expectedStream);

        Tree originalTree = new Tree.Builder(storage).fromDirectory(getResourcePath(original)).create();
        Tree revisedTree = new Tree.Builder(storage).fromDirectory(getResourcePath(revised)).create();
        List<String> actualLines = treeDiffer.diff(originalTree, revisedTree);

        assertEquals(expectedLines, actualLines);
    }

    private static Path getResourcePath(String name) throws URISyntaxException {
        // FIXME: 16.04.16 doesn't work for .jar resources
        return Paths.get(TreeDifferTest.class.getResource(name).toURI());
    }
}
@@ -588,16 +588,46 @@
 .Paths;%0A
+import java.util.Collections;%0A
 import j
@@ -641,16 +641,16 @@
 l.List;%0A
-
 %0Aimport 
@@ -1010,16 +1010,56 @@
 th(%22%22)).
+filter(path -%3E Files.isDirectory(path)).
 map(path
@@ -1429,32 +1429,190 @@
 ows Exception %7B%0A
+        List%3CString%3E expectedLines;%0A        if (original.equals(revised)) %7B%0A            expectedLines = Collections.emptyList();%0A        %7D%0A        else %7B%0A    
         InputStr
@@ -1698,16 +1698,20 @@
         
+    
 assumeNo
@@ -1737,36 +1737,27 @@
 m);%0A        
-List%3CString%3E
+   
  expectedLin
@@ -1795,16 +1795,26 @@
 Stream);
+%0A        %7D
 %0A%0A      

Test every tree against itself