package ch.zhaw.ads;

import org.junit.Test;
import org.junit.Before;
import static org.junit.Assert.*;

public class TreeTest {
    Tree<String> tree;

    @Before
    public void setUp() throws Exception {
        tree = new SortedBinaryTree<String>();
        tree.add("B");
        tree.add("A");
        tree.add("C");
        tree.add("D");
    }

    @Test
    public void testInorder() {
        Visitor<String> v = new MyVisitor<String>();
        tree.traversal().inorder(v);
        assertEquals("inorder", "ABCD", v.toString());
    }

    @Test
    public void testPreorder() {
        Visitor<String> v = new MyVisitor<String>();
        tree.traversal().preorder(v);
        assertEquals("preorder", "BACD", v.toString());
    }

    @Test
    public void testPostorder() {
        Visitor<String> v = new MyVisitor<String>();
        tree.traversal().postorder(v);
        assertEquals("postorder", "ADCB", v.toString());
    }

    @Test
    public void testLevelorder() {
        Visitor<String> v = new MyVisitor<String>();
        tree.traversal().levelorder(v);
        assertEquals("levelorder", "BACD", v.toString());
    }

    @Test
    public void testInterval() {
        Comparable<Integer> minComparable = new MyComparable(1);
        Comparable<Integer> maxComparable = new MyComparable(9);
        Visitor<Integer> v = new MyVisitor<Integer>();
        Tree<Integer> mytree = new SortedBinaryTree<Integer>();
        mytree.add(10);
        mytree.add(7);
        mytree.add(14);
        mytree.add(17);
        mytree.add(12);
        mytree.add(6);
        mytree.add(8);
        mytree.add(4);

        mytree.traversal().interval(minComparable, maxComparable, v);
        assertEquals("interval", "7648", v.toString());
    }
}

class MyComparable implements Comparable<Integer> {
    Integer value;

    public MyComparable(Integer value) {
        this.value = value;
    }

    @Override
    public int compareTo(Integer other) {
        return this.value.compareTo(other);
    }
}


class MyVisitor<T> implements Visitor<T> {
    StringBuilder output;

    MyVisitor() {
        output = new StringBuilder();
    }

    public void visit(T s) {
        output.append(s);
    }

    public String toString() {
        return output.toString();
    }
}
