package ws.prova.reference;

/*
 * Copyright (C) 1999-2005 <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 org.mandarax.kernel.*;
import org.mandarax.util.TermIterator;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Reference implementation for variable terms.
 *
 * @author <A HREF="mailto:mandarax@jbdietrich.com">Jens Dietrich</A>
 * @author <A HREF="mailto:a.kozlenkov@city.ac.uk">Alex Kozlenkov</A>
 * @version 3.3.1 <9 August 2004>
 * @since 1.1
 *        Prova re-integration modifications
 */
public class VariableTermImpl extends LObject implements VariableTerm {

	private String name = null;
	private Class type = null;

	/**
	 * Cache the string representation for optimized debugging.
	 */
	private transient String cachedToString = null;

	/**
	 * Create a new instance with the name and the type passed as parameter.
	 */
	public VariableTermImpl() {
		super();
	}

	/**
	 * Create a new instance with the name and the type passed as parameter.
	 *
	 * @param n the name of the variable
	 * @param t the type of the variable
	 */
	VariableTermImpl(String n, Class t) {
		super();
		setName(n);
		setType(t);
	}

	/**
	 * Get a (trivial) term iterator for the subterms.
	 *
	 * @return an iterator for all sub terms
	 */
	public TermIterator allSubterms() {
		Term[] t = {this};

		return new TermIterator(t);
	}

	/**
	 * Apply a replacement to a term.
	 *
	 * @param r the replacement
	 * @return the term resulting from applying the replacement
	 */
	public Term apply(Replacement r) {
		if (r.original.sameAs(this)) {
			return r.replacement;
		} else {
			return this;
		}
	}

	public void getAllSubtermsA(List result) {
		result.add(this);
	}

	public void getAllSubtermsA(List result, boolean left) {
		result.add(this);
	}

	public boolean getAllSubtermsB(List result, Iterator aux) {
		Object t = org.mandarax.reference.ConstantTermImpl.nextNotNull(aux);
		if (t != null) {
			result.add(this);
			return (t instanceof VariableTermImpl) && (this == t);
		}
		return false;
	}

	public boolean getAllSubtermsB(List result, Iterator aux, boolean left) {
		Object t = ConstantTermImpl.nextNotNull(aux);
		if (t != null) {
			result.add(this);
			return (t instanceof VariableTermImpl) && (this == t);
		}
		return false;
	}

	/**
	 * Indicates whether the term containes variables.
	 *
	 * @return true
	 */
	public boolean containsVariables() {
		return true;
	}

	/**
	 * Indicates whether the term contains the provided variable term.
	 *
	 * @param var a variable term
	 * @return true if the term contains the variable term provided, false otherwise
	 */
	public boolean containsVariable(VariableTerm var) {
		return this == var;
	}

	/**
	 * Indicates whether the objects are equal.
	 *
	 * @param t the object to compare this object with
	 * @return true if the objects are equal, false otherwise
	 */
	public boolean equals(Object t) {
		if (!(t instanceof VariableTerm)) {
			return false;
		}

		return type.equals(((VariableTerm) t).getType())
				&& name.equals(((VariableTerm) t).getName());
	}

	/**
	 * Get all subterms as array.
	 *
	 * @return an array of terms only containing this object
	 */
	public Term[] getAllSubterms() {
		Term[] t = {this};

		return t;
	}

	/**
	 * Get the name of the variable.
	 *
	 * @return the name of the variable
	 */
	public String getName() {
		return name;
	}

	/**
	 * Get the type of the variable.
	 *
	 * @return the term type
	 */
	public Class getType() {
		return type;
	}

	/**
	 * Returns the hashcode of the object.
	 *
	 * @return the hash value
	 */
	public int hashCode() {
		return type.hashCode() ^ name.hashCode() * 31;
	}

	/**
	 * Indicates whether the term is compound.
	 *
	 * @return false
	 */
	public boolean isCompound() {
		return false;
	}

	/**
	 * Indicates whether the term is constant.
	 *
	 * @return false
	 */
	public boolean isConstant() {
		return false;
	}

	/**
	 * Indicates whether the object (usually a term or a clause set) can be performed
	 * using the java semantics. Variable terms do not support the java semantics!
	 *
	 * @return false
	 */
	public boolean isExecutable() {
		return false;
	}

	/**
	 * Indicates whether the term is a variable.
	 *
	 * @return true
	 */
	public boolean isVariable() {
		return true;
	}

	/**
	 * Resolve a constant term. This is trivial: just
	 * throw an excpetion (variables cannot be resolved).
	 *
	 * @param session a session object
	 * @return the result of resolving the term
	 * @throws UnsupportedOperationException
	 * @throws IllegalArgumentException
	 */
	public Object resolve(Session session) throws UnsupportedOperationException, IllegalArgumentException {
		throw new UnsupportedOperationException();
	}

//	/**
//	 * Resolve a constant term. This is trivial: just
//	 * throw an excpetion (variables cannot be resolved).
//	 * @return the result of resolving the term
//	 * @throws java.lang.UnsupportedOperationException
//	 * @throws java.lang.IllegalArgumentException
//	 */
//	public Object resolve()
//			throws UnsupportedOperationException, IllegalArgumentException {
//		throw new UnsupportedOperationException ();
//	}

	/**
	 * Indicates whether the object is the same as the parameter.
	 *
	 * @param t another term
	 * @return true if the both objects are the same
	 */
	public boolean sameAs(Term t) {
		if (!(t instanceof VariableTerm)) {
			return false;
		}

		return type.equals(((VariableTerm) t).getType())
				&& name.equals(((VariableTerm) t).getName());
	}

    /**
     * Set a name.
     *
     * @param n the new name
     */
    public void setName(String n) {
        name = n;
    }

	/**
	 * Set a type.
	 *
	 * @param t the type
	 */
	public void setType(Class t) {
		type = t;
	}

	/**
	 * Convert the receiver to a string.
	 *
	 * @return the string representation of this object
	 */
	public String toString() {
		if (cachedToString == null) {
			StringBuffer buf = new StringBuffer();

			buf.append("<");
			if( name.indexOf("::")>=0 ) {
				buf.append(name.replaceAll("::","."));
			} else {
				if( type!=Object.class && type!=ws.prova.RList.class ) {
					buf.append(type.getName());
					buf.append(".");
				}
				buf.append(name);
			}
			buf.append(">");

			cachedToString = new String(buf);
		}
		return cachedToString;
	}

	/**
     * Apply a minimal (least intrusive) substitution to a term.
     * @return the term resulting from applying the replacement
     * @param r a replacement
     */
    public Term applyMinimally(Collection r, Map complexReplacements) {
		for (java.util.Iterator it = r.iterator(); it.hasNext();) {
			Replacement rep = (Replacement) it.next();
			if( rep.original.sameAs(this) )
				return rep.replacement.applyMinimally(r,complexReplacements);
		}
    	return this;
    }
}
