package trees;

public class TernaryNode<K extends Comparable<K>, V> implements INode<K, V> {

	private K m_leftKey;
	private V m_leftValue;
	private K m_rightKey;
	private V m_rightValue;
	
	private INode<K, V> m_left;
	private INode<K, V> m_middle;
	private INode<K, V> m_right;
	
	
	
	public TernaryNode(K m_leftKey, V m_leftValue, K m_rightKey,
			V m_rightValue, INode<K, V> m_left, INode<K, V> m_middle,
			INode<K, V> m_right) {
		super();
		this.m_leftKey = m_leftKey;
		this.m_leftValue = m_leftValue;
		this.m_rightKey = m_rightKey;
		this.m_rightValue = m_rightValue;
		this.m_left = m_left;
		this.m_middle = m_middle;
		this.m_right = m_right;
	}

	
	
	public TernaryNode(K m_leftKey, V m_leftValue, K m_rightKey, V m_rightValue) {
		super();
		this.m_leftKey = m_leftKey;
		this.m_leftValue = m_leftValue;
		this.m_rightKey = m_rightKey;
		this.m_rightValue = m_rightValue;
		
		this.m_left = new Leaf<K, V>();
		this.m_middle = new Leaf<K, V>();
		this.m_right = new Leaf<K, V>();
	}



	public V search(K key) {
		int cmpL = key.compareTo(m_leftKey);
		if(cmpL == 0) return m_leftValue;
		else if(cmpL < 0) return m_left.search(key);
		
		int cmpR = key.compareTo(m_rightKey);
		if(cmpR == 0) return m_rightValue;
		else if(cmpR < 0) return m_middle.search(key);
		else return m_right.search(key);
	}


	public INode<K, V> insert(K key, V value) {
		int cmpL = key.compareTo(m_leftKey);
		if(cmpL == 0) return this;
		if(cmpL < 0) m_left = m_left.insert(key, value);
		else {
			int cmpR = key.compareTo(m_rightKey);
			if(cmpR == 0) return this;
			if(cmpR < 0) m_middle = m_middle.insert(key, value);
			else m_right = m_right.insert(key, value);
		}
		return this;
	}
	
	public String toString()
	{
		
		return "Ternary[" + m_leftKey + " -> " + m_leftValue + " | " + m_rightKey + " -> " + m_rightValue + "]("
				+ m_left + ", " + m_middle + ", " + m_right + ")";
	}


}
