view src/treecms/proto/edit/EditableTreeBuilder.java @ 21:cce963b8a4fd

EditableTreeBuilderTest1
author ShoshiTAMAKI
date Sun, 17 Oct 2010 13:56:47 +0900
parents e950264f82d3
children 9b91329e8a04
line wrap: on
line source

package treecms.proto.edit;

import java.util.LinkedList;
import java.util.List;

import treecms.proto.api.Node;
import treecms.proto.api.TreeBuilder;

public class EditableTreeBuilder implements TreeBuilder
{
	private TreeBuilder m_builder;
	private Node m_newRoot;
	private Node m_oldRoot;
	
	private Node m_target; //node that wanted to edit.
	
	public EditableTreeBuilder(Node _target,TreeBuilder _builder)
	{
		m_builder = _builder;
		
		//search path
		m_oldRoot = _builder.getContents();
		LinkedList<Node> path = findPath(m_oldRoot,_target);
		
		/*
		for(Node node : path){
			System.out.println(node.getTitle());
		}
		*/
		
		//clone tree
		
		//clone root node.
		m_newRoot = m_builder.createNode();
		Node oldRoot = path.poll();
		m_newRoot.setClassName(oldRoot.getClassName());
		m_newRoot.setTitle(oldRoot.getTitle());
		m_newRoot.getChildList().addAll(oldRoot.getChildList());
		
		cloneTree(path,m_newRoot.getChildList());
	}
	
	public Node getTargetNode()
	{
		return m_target;
	}
	
	private void cloneTree(LinkedList<Node> _path,List<Node> _children)
	{
		Node target = _path.poll();
		for(int i = 0;i < _children.size();i ++){
			Node _child = _children.get(i);
			if(_child == target){
				//clone node
				Node newNode = m_builder.createNode();
				newNode.setClassName(target.getClassName());
				newNode.setTitle(target.getTitle());
				newNode.getChildList().addAll(target.getChildList());
				m_target = newNode; //oooooooooooooo.............. :(
				
				//remove old node from clonedTree
				_children.add(i,newNode);
				_children.remove(target);
				
				cloneTree(_path,newNode.getChildList());
				
				break;
			}
		}
	}
	
	public List<Node> findPathTest(Node _root,Node _child)
	{
		return findPath(_root,_child);
	}
	
	private LinkedList<Node> findPath(Node _root,Node _child)
	{
		LinkedList<Node> list = new LinkedList<Node>();
		findPath(_root,_child,list);
		list.addFirst(_root);
		return list;
	}
	
	private boolean findPath(Node _root,Node _child,LinkedList<Node> _list)
	{
		if(_root == _child){
			return true;
		}
		
		for(Node child : _root.getChildList()){
			if(findPath(child,_child,_list)){
				_list.addFirst(child);
				return true;
			}
		}
		return false;
	}

	@Override
	public Node getContents()
	{
		// TODO Auto-generated method stub
		return m_newRoot;
	}

	@Override
	public Node createNode()
	{
		// TODO Auto-generated method stub
		return m_builder.createNode();
	}
}