package com.github.davidmoten.logan;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;

import java.io.File;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

import org.junit.Test;

import com.github.davidmoten.bplustree.BPlusTree;

public class DataPersisted2Test {

    @Test
    public void test() {
        BPlusTree<IntWithTimestamp, PropertyWithTimestamp> tree = create();
        tree.insert(new IntWithTimestamp(123, 500L), new PropertyWithTimestamp("hello", 1.1, 500L));
        tree.insert(new IntWithTimestamp(234, 200L), new PropertyWithTimestamp("there", 1.2, 200L));
        tree.insert(new IntWithTimestamp(124, 300L), new PropertyWithTimestamp("hello2", 1.3, 300L));
        tree.print();

        Iterator<PropertyWithTimestamp> it = tree.find( //
                new IntWithTimestamp(123, 0), //
                new IntWithTimestamp(123, 1000)) //
                .iterator();
        assertEquals(500L, it.next().time);
        assertFalse(it.hasNext());
    }

    @Test
    public void testTreeSet() {
        TreeSet<IntWithTimestamp> set = new TreeSet<>();
        set.add(new IntWithTimestamp(123, 100L));
        set.add(new IntWithTimestamp(234, 200L));
        set.add(new IntWithTimestamp(124, 300L));
        List<Long> list = set.stream().map(x -> x.time).collect(Collectors.toList());
        assertEquals(Arrays.asList(100L, 300L, 200L), list);
    }

    private BPlusTree<IntWithTimestamp, PropertyWithTimestamp> create() {
        File dir = new File("target/testbp");
        dir.mkdirs();
        for (File f : dir.listFiles()) {
            f.delete();
        }

        return BPlusTree.file() //
                .directory(dir) //
                .maxKeys(12) //
                .segmentSizeMB(1) //
                .keySerializer(IntWithTimestamp.SERIALIZER) //
                .valueSerializer(PropertyWithTimestamp.SERIALIZER) //
                .naturalOrder();
    }

}
@@ -828,16 +828,30 @@
 int();%0A%0A
+        %7B%0A    
         
@@ -909,32 +909,36 @@
                 
+ 
+   
 new IntWithTimes
@@ -950,24 +950,28 @@
 123, 0), //%0A
+    
             
@@ -1026,16 +1026,20 @@
         
+    
 .iterato
@@ -1043,32 +1043,36 @@
 ator();%0A        
+   
+ 
 assertEquals(500
@@ -1095,24 +1095,28 @@
 e);%0A        
+    
 assertFalse(
@@ -1126,24 +1126,441 @@
 hasNext());%0A
+        %7D%0A        %7B%0A            Iterator%3CPropertyWithTimestamp%3E it = tree.find( //%0A                    new IntWithTimestamp(0, 0), //%0A                    new IntWithTimestamp(1000, 1000)) //%0A                    .iterator();%0A            assertEquals(500L, it.next().time);%0A            assertEquals(300L, it.next().time);%0A            assertEquals(200L, it.next().time);%0A            assertFalse(it.hasNext());%0A        %7D%0A
     %7D%0A%0A    @

add test