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.ArrayList;
import java.util.List;
import org.mandarax.kernel.Clause;
import org.mandarax.kernel.Derivation;
import org.mandarax.kernel.Replacement;
import org.mandarax.kernel.Result;
import org.mandarax.kernel.Term;
import org.mandarax.util.CachedResultSet;

/**
 * Implementation of a result set for ResolutionInferenceEngine2. Could be an inner class, the only
 * reason to have it as a separate class is that tool support (e.g. debugging) for separate classes is better.
 * @author <A HREF="mailto:mandarax@jbdietrich.com">Jens Dietrich</A>
 * @version 3.3.1 <9 August 2004>
 * @since 1.8
 */
class ResultSetImpl2 extends CachedResultSet {


	/**
	 * Constructor
	 * @param root the root of the derivation
	 * @param resultNodes a list of result nodes
	 * @param query the query
	 */
	ResultSetImpl2(DerivationNodeImpl root, List resultNodes, Clause query) {
		super();

		// root.dump(System.out);
		vars = IEUtils.getVars(query);
		
		if (vars.isEmpty()) {
			// fully instanciated queries !
			// @todo remove limitation: at most one derivation (different proofs are not shown)
			results = new ArrayList(1);
			if (!root.isFailed()) results.add(new Result(new Derivation(root,0),new Replacement[0]));
		}
		else {
			// variables in queries - must apply var replacements from nodes
			Term[] varArray = (Term[]) vars.toArray(new Term[0]);
			results = new ArrayList(resultNodes.size());
			int resultNumber = 0;
			List[] repls = new List[varArray.length];
			for (int i = 0; i < repls.length; i++) repls[i] = new ArrayList();
			root.replace(repls, varArray);
			resultNumber = repls.length==0?0:repls[0].size();
	
	
			// DerivationNodeImpl proofRootNode = (new DerivationTreeBuilder()).buildTree(root);
			for (int i = 0; i < resultNumber; i++) {
				Replacement[] replacements = new Replacement[varArray.length];
				for (int j = 0; j < varArray.length; j++) {
					replacements[j] = new Replacement(varArray[j], (Term) repls[j].get(i));
				}
				Result result = new Result(new Derivation(root,results.size()), replacements);
				results.add(result);
			}
		}
	}
}
