package org.mandarax.reference;

/*
 * Copyright (C) 1999-2004 <a href="mailto:mandarax@jbdietrich.com">Jens Dietrich</a>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
import java.util.Iterator;
import java.util.Stack;
import java.util.Vector;

import org.mandarax.kernel.Clause;

/**
 * Builder for a derivation tree. Takes the root node of a linear
 * derivation as input and outputs the root node of the derivation
 * tree.
 * @author <A HREF="mailto:mandarax@jbdietrich.com">Jens Dietrich</A>
 * @version 3.3.1 <9 August 2004>
 * @since 1.0
 */
final class DerivationTreeBuilder {

	private class XDerivationNode extends org.mandarax.reference.DerivationNodeImpl {

		public int     expectedSubnodes = 0;
		public boolean isFailedLeave    = false;
		public boolean expectsMoreSubnodes() {
			return expectedSubnodes < getSubNodes ().size ();
		}
	}

	/**
	 * Constructor.
	 */
	public DerivationTreeBuilder() {
		super ();
	}
	/**
	 * Build a derivation tree.
	 * @return the root of the derivation tree
	 * @param oldRoot the first node of a (linear) chain of nodes
	 */
	public DerivationNodeImpl buildTree(DerivationNodeImpl oldRoot) {
		java.util.Vector linearNodes = linearize (oldRoot);

		linkNodes (linearNodes, new java.util.Stack (), 0);

		return(DerivationNodeImpl) linearNodes.elementAt (0);
	}
	/**
	 * Linearize the derivation nodes.
	 * @return a collection
	 * @param oldRoot a derivation node
	 */
	private java.util.Vector linearize(DerivationNodeImpl oldRoot) {
		Vector coll = new Vector ();

		linearize (oldRoot, coll);

		return coll;
	}
	/**
	 * Linearize the derivation nodes.
	 * @param aNode a derivation node
	 * @param aCollection a collection
	 */
	private void linearize(DerivationNodeImpl aNode,java.util.Vector aCollection) {

		// first build a new XNode for aNode and add it to the collection
		XDerivationNode aNewNode = new XDerivationNode ();

		aNewNode.setFailed (aNode.isFailed ());
		aNewNode.setUnification (aNode.getUnification ());

		Clause applied = aNode.getAppliedClause ();

		aNewNode.setAppliedClause (applied);
		aNewNode.setQuery (aNode.getQuery ());

		aNewNode.expectedSubnodes = (applied == null)
									? 1
									: applied.getNegativeLiterals ().size ();
		aNewNode.isFailedLeave    = aNode.isFailed ()
									&& aNode.getSubNodes ().isEmpty ();

		aCollection.addElement (aNewNode);

		// then add all subnodes
		for(Iterator it = aNode.getSubNodes ().iterator (); it.hasNext (); ) {
			linearize ((DerivationNodeImpl) it.next (), aCollection);
		}
	}
	/**
	 * Link the nodes in the structure.
	 * @param nodes a collection of nodes
	 * @param stack stack of nodes
	 * @param index the position
	 */
	private void linkNodes(Vector nodes, Stack stack, int index) {

		// handling if stack is empty
		if((nodes.size () == index) || (stack.isEmpty () && (index > 0))) {
			return;
		}

		// handling if index is 0 (root node)
		if(index == 0) {
			XDerivationNode rootNode = (XDerivationNode) nodes.elementAt (0);

			if(rootNode.expectedSubnodes > 0) {
				stack.push (rootNode);
				linkNodes (nodes, stack, 1);
			}

			return;
		}

		// general case
		XDerivationNode aNode = (XDerivationNode) nodes.elementAt (index);
		XDerivationNode previousNode = (XDerivationNode) stack.peek();
		previousNode.addSubNode (aNode);

		if(aNode.isFailed ()) {
			if(aNode.isFailedLeave) {
				removeAllFailedNodes (stack);
			} else {
				if(aNode.expectedSubnodes > 0) {
					stack.push (aNode);
				}
			}
		} else {
			previousNode.expectedSubnodes = previousNode.expectedSubnodes - 1;

			if(previousNode.expectedSubnodes == 0) {
				stack.pop ();
			}

			if(aNode.expectedSubnodes > 0) {
				stack.push (aNode);
			}
		}

		linkNodes (nodes, stack, index + 1);
	}
	/**
	 * Remove all failed nodes from a stack.
	 * @param stack the stack of nodes
	 */
	private void removeAllFailedNodes(Stack stack) {
		if(stack.size () == 0) return;
		XDerivationNode top = (XDerivationNode) stack.peek();
		if(top.isFailed ()) {
			stack.pop ();
			removeAllFailedNodes (stack);
		}

		return;
	}
}
