package BTree;

public class BTreeCS extends BTreeCA {

	private BTreeCS parentTree;
	
	public BTreeCS (Integer value, BTreeCA leftTree, BTreeCA rightTree) {
		super(value, leftTree, rightTree);
		this.parentTree = this;
	}
	
	public BTreeCS() {
		super(null,null,null);
		this.parentTree = this;
	}
	
	public BTreeCS(Integer value) {
		super(value);
		this.parentTree = this;
	}
	
	@Override
	public boolean isEmpty() {
		return value == null;
	}

	@Override
	public BTree getRoot() throws Exception {
		BTreeCS currentTree = this;
		while(currentTree.parentTree != currentTree) {
			currentTree = currentTree.parentTree;
		}
		return currentTree;
	}

	@Override
	public int getLeftValue() throws Exception {
		if(this.isEmpty()) {
			throw new IllegalStateException("L'arbre gauche est vide");
		}
		else {
			return this.leftTree.getValue();
		}
	}

	@Override
	public int getRightValue() throws Exception {
		if(this.isEmpty()) {
			throw new IllegalStateException("L'arbre droit est vide");
		}
		else {
			return this.rightTree.getLeftValue();
		}
	}

	@Override
	public void setLeftTree(BTree leftTree) throws Exception {
		if(leftTree.getClass() != this.getClass()) {
			throw new IllegalArgumentException("L'arguement a un type invalide");
		}
		if(!this.leftTree.isEmpty()) {
			throw new IllegalStateException("L'arbre gauche n'est pas libre");
		}
		else {			
			BTreeCS leftTreeCS = (BTreeCS) leftTree;
			leftTreeCS.parentTree = this;
			this.leftTree = leftTreeCS;
		}
	}

	@Override
	public void setRightTree(BTree rightTree) throws Exception {
		if(rightTree.getClass() != this.getClass()) {
			throw new IllegalArgumentException("L'arguement a un type invalide");
		}
		if(!this.rightTree.isEmpty()) {
			throw new IllegalStateException("L'arbre droit n'est pas libre");
		}
		else {
			BTreeCS rightTreeCS = (BTreeCS) rightTree;
			rightTreeCS.parentTree = this;
			this.leftTree = rightTreeCS;
		}
	}

	@Override
	public void setLeftValue(int leftSubRoot) throws Exception {
		if(this.isEmpty()) {
			throw new IllegalStateException("Arbre vide");
		}
		if(!this.leftTree.isEmpty()) {
			throw new IllegalStateException("Arbre gauche vide");
		}
		else {
			this.leftTree.value = leftSubRoot;
			this.leftTree.leftTree = new BTreeCA();
			this.leftTree.rightTree = new BTreeCA();
		}
		
	}

	@Override
	public void setRightValue(int rightSubRoot) throws Exception {
		if(this.isEmpty()) {
			throw new IllegalStateException("Arbre vide");
		}
		if(!this.rightTree.isEmpty()) {
			throw new IllegalStateException("Arbre droit vide");
		}
		else {
			this.rightTree.value = rightSubRoot;
			this.rightTree.leftTree = new BTreeCA();
			this.rightTree.rightTree = new BTreeCA();
		}
		
	}

}
