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 constant 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 ConstantTermImpl extends LObject implements ConstantTerm {

	private Object object = null;
	private Class type = null;

	/**
	 * Create a new constant term.
	 */
	public ConstantTermImpl() {
		super();
	}

	/**
	 * Create a new constant term on a object.
	 * [Prova] Made public to be callable from ws.prova.reference.ResolutionInferenceEngine5
	 *
	 * @param o an object
	 */
	public ConstantTermImpl(Object o) {
		super();
		setObject(o);
	}

	/**
	 * Create a new constant term on a object.
	 *
	 * @param o an object
	 * @param t the type of the object
	 * @throws an illegal argument exception is thrown if o is not an instance of t
	 */
	ConstantTermImpl(Object o, Class t) {
		super();
		setObject(o);
		setType(t);
	}

	/**
	 * Get a (rather trivial) term iterator for the subterms.
	 *
	 * @return org.mandarax.util.TermIterator
	 */
	public TermIterator allSubterms() {
		Term[] t = new Term[1];
		t[0] = this;
		return new TermIterator(t);
	}

	/**
	 * Apply a replacement to a term.
	 * Note that constants cannot be replaced!
	 *
	 * @param r org.mandarax.kernel.Replacement
	 * @return org.mandarax.kernel.Term
	 */
	public Term apply(Replacement r) {
		return this;
	}

	public void getAllSubtermsA(List result) {
		result.add(this);
	}
//	public void getAllSubtermsA( List result, List vars ) {
//		result.add( this );
//		vars.add( null );
//	}

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

	public boolean getAllSubtermsB(List result, Iterator aux) {
		Object t = nextNotNull(aux);
		if (t != null) {
			if (t instanceof ConstantTermImpl) {
				if (getObject().equals(((ConstantTerm) t).getObject())) {
					aux.remove();
					return true;
				}
			}
			result.add(this);
		}
		return false;
	}

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

	static public Object nextNotNull(Iterator it) {
		Object t = null;
		if (it.hasNext()) {
			t = it.next();
		}
		return t;
	}

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

	/**
	 * 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 false;
	}

	/**
	 * Indicates whether the object equals the parameter.
	 *
	 * @param obj java.lang.Object
	 * @return boolean
	 */
	public boolean equals(Object obj) {
		if (!(obj instanceof ConstantTerm)) {
			return false;
		}

		return object.equals(((ConstantTerm) obj).getObject());
	}

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

		return t;
	}

	/**
	 * Get the object.
	 *
	 * @return the wrapped object
	 */
	public Object getObject() {
		return object;
	}

	/**
	 * Get the type of the term.
	 *
	 * @return the term type
	 */
	public Class getType() {
		// bugfix in 3.3.1 by Jens
		return type == null ? object.getClass() : type;
	}

	/**
	 * Get the hash code of the object.
	 *
	 * @return the hash value
	 */
	public int hashCode() {
		return (object == null)
				? 0
				: object.hashCode();
	}

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

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

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

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

	/**
	 * Resolve a constant term. This is trivial: just
	 * return the object.
	 *
	 * @param session a session object
	 * @return the result of resolving the term
	 * @throws UnsupportedOperationException
	 * @throws IllegalArgumentException
	 */
	public Object resolve(Session session) throws UnsupportedOperationException, IllegalArgumentException {
		return getObject();
	}

//	/**
//	 * Resolve a constant term. This is trivial: just
//	 * return the object.
//	 * @return the result of resolving the term
//	 * @throws java.lang.UnsupportedOperationException
//	 * @throws java.lang.IllegalArgumentException
//	 */
//	public Object resolve()
//			throws UnsupportedOperationException, IllegalArgumentException {
//		return getObject ();
//	}

	/**
	 * 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 ConstantTerm)) {
			return false;
		}

		return object.equals(((ConstantTerm) t).getObject());
	}

    /**
     * Set the object.
     *
     * @param obj the object that is to be wrapped
     * @throws an illegal argument exception is thrown if the object is not an instance of
     *            the type previously set using setType()
     */
    public void setObject(Object obj) {
        if ((type != null) && !(type.isAssignableFrom(obj.getClass()))) {
            throw new IllegalArgumentException("Object " + obj
                    + " and type " + type
                    + " are inconsistent");
        }

        object = obj;
    }

	/**
	 * Set the type.
	 *
	 * @param t the type
	 * @throws an illegal argument exception is thrown if the object previously set using setObject() is not an instance of
	 *            the type
	 */
	public void setType(Class t) {
		if ((object != null) && !(t.isAssignableFrom(object.getClass()))) {
			throw new IllegalArgumentException("Object " + object
					+ " and type " + t
					+ " are inconsistent");
		}

		type = t;
	}

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

		buf.append("[");
		buf.append(object.toString());
		buf.append("]");

		return new String(buf);
	}

    /**
     * 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) {
    	return this;
    }
    
}
