package de.dass_it.vanhelsing.gui;

import java.util.Enumeration;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

import de.dass_it.vanhelsing.gui.items.ConcreteUserObjectItem;
import de.dass_it.vanhelsing.gui.items.ItemType;
import de.dass_it.vanhelsing.gui.items.UserObjectItem;
import de.dass_it.vanhelsing.gui.items.UserObjectItemType;

public class DataTree {
	private DefaultTreeModel tree;
	private DefaultMutableTreeNode root;
	
	public DataTree() {}
	
	public void setTree(String name){
		setRoot(new DefaultMutableTreeNode());
		tree = new DefaultTreeModel(root);
		UserObjectItemType userType = new UserObjectItemType(root);
		ConcreteUserObjectItem obj = new ConcreteUserObjectItem();
		root.setUserObject(userType);
		userType.setUserObject(obj);
		userType.setLeaf(false);
		obj.setResName(name);
	}
	public DefaultMutableTreeNode createNode(DefaultMutableTreeNode parent, UserObjectItem userObject){
		DefaultMutableTreeNode node = new DefaultMutableTreeNode();
		UserObjectItemType uoit = new UserObjectItemType(node);
		node.setUserObject(uoit);
		uoit.setUserObject(userObject);
		parent.add(node);
		((UserObjectItemType)parent.getUserObject()).setLeaf(false);
		return node;
	}
	public void updateNode(DefaultMutableTreeNode node, UserObjectItem userObject){
		node.setUserObject(userObject);
	}
	public DefaultMutableTreeNode getNodeById(int id){
  		DefaultMutableTreeNode node;
  		int resId = new Integer(id);
  		Enumeration<DefaultMutableTreeNode> e = root.depthFirstEnumeration();
  		
  		while (e.hasMoreElements()){
  			node = e.nextElement();
  			if (resId ==((ConcreteUserObjectItem)(((UserObjectItemType)node.getUserObject()).
  					getUserObject())).getResId()) {
  				return node;
  			}
  		}
  		return null;
	}
	public DefaultMutableTreeNode getNodeByName(String name){
  		DefaultMutableTreeNode node;
  		Enumeration<DefaultMutableTreeNode> e = root.depthFirstEnumeration();
  		
  		while (e.hasMoreElements()){
  			node = e.nextElement();
  			if (name.equals(((ConcreteUserObjectItem)(((UserObjectItemType)node.getUserObject())
  					.getUserObject())).getResName())) {
  				return node;
  			}
  		}
  		return null;
	}
	public DefaultMutableTreeNode deleteNode(DefaultMutableTreeNode node) throws constraintValidationException{
		if (node.getChildCount()>0) throw new constraintValidationException();
		DefaultMutableTreeNode parent = (DefaultMutableTreeNode) node.getParent();
		parent.remove(node);
		return node;
	}
	public DefaultMutableTreeNode getRoot(){
		return root;
	}
	public void setRoot(DefaultMutableTreeNode root){
		this.root = root;
	}
	public DefaultTreeModel getTree() {
		return tree;
	}
	public void setTree(DefaultTreeModel tree) {
		this.tree = tree;
	}
}
