package hw05;

public class BinaryTree {
	private Car payload;
	private BinaryTree left;
	private BinaryTree right;

	public BinaryTree(Car payload) {
		this.payload = payload;
		this.left = null;
		this.right = null;
	}


	public void insertByDate(Car newCar) {
		if (newCar.year < payload.year) {
			if (left == null) left=new BinaryTree(newCar);
			else left.insertByDate(newCar);
		} else {
			if (right == null) right=new BinaryTree(newCar);
			else right.insertByDate(newCar);
		}
	}

	public void insertByMake(Car newCar) {
		if (newCar.make.compareTo(payload.make) < 0) {
			if (left == null) left=new BinaryTree(newCar);
			else left.insertByMake(newCar);
		} else {
			if (right == null) right=new BinaryTree(newCar);
			else right.insertByMake(newCar); // Bug 3
		}
	}

	public void insertByOwner(Car newCar) {
		if (newCar.owner.compareTo(payload.owner) < 0) {
			if (left == null) left=new BinaryTree(payload);
			else left.insertByOwner(newCar);
		} else {
			if (right == null) right=new BinaryTree(newCar);
			else right.insertByOwner(newCar);
		}
	}

	public int size() {
		int sum=1;
		if (left!=null) sum+=left.size();
		if (right != null) sum +=right.size();
		return sum;
	}

	public int depth() {
		int dl=0; // Bug 1: dl and dr were initialized to 1, should be 0 
		if (left!=null) dl=left.depth();
		int dr=0;
		if (right!=null) dr=right.depth();
		return 1+(dl>dr?dl:dr);
	}

	@Override
	public String toString() {
		String result = "";
		if (left != null) result = left.toString() + "; ";
		result += payload.toString();
		if (right != null) result += right.toString() + "; ";
		return result;
	}

	public String position(Car car) {
		if (this.payload.equals(car)) return "*";
		if (left!=null) {
			String leftpos = left.position(car);
			if (leftpos != null) return "L"+leftpos;
			// else return "R*"; 2nd bug... don't assume car is in right subtree
		}
		if (right!=null) {
			String rightpos = right.position(car);
			if (rightpos != null) return "R" + rightpos;
		}
		return null;
	}

	public void printGraph() {
		printGraph("","","");
	}

	private void printGraph(String b4root, String atRoot, String aftRoot) {
		if (left!=null) {
			left.printGraph(b4root+"   ",b4root+"  -",b4root+"  |");
		}
		System.out.println(atRoot + payload.toString());
		if (right!=null) {
			right.printGraph(aftRoot+"  |",aftRoot+"  -",aftRoot+"   ");
		}
	}

}
