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.apache.commons.collections.iterators.IteratorChain;
import org.mandarax.kernel.*;
import org.mandarax.util.SingleClauseSetIterator;

import java.util.*;

/**
 * Reference implementation for rules.
 *
 * @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 RuleImpl extends AbstractClause implements Rule, ClauseSetChangeListener {

	private Fact head = null;
	private List posLiterals = null;
	private List body = new ArrayList();
	private static String IF = "IF";
	private static String THEN = "THEN";
	private static String AND = "AND";
	private static String OR = "OR";
	private boolean prerequisitesConnectedByOr = false;
	private boolean isBound;

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

	/**
	 * Constructor.
	 */
	public RuleImpl() {
		super();
	}

	/**
	 * Constructor. Pass a head and a body.
	 *
	 * @param c a list of facts that is going to be the body of the rule
	 * @param h a fact that is going to be the head of the rule
	 */
	RuleImpl(List c, Fact h) {
		super();
		setBody(c);
		setHead(h);
	}

	/**
	 * Constructor. Pass a head and a body.
	 *
	 * @param c  a list of facts that is going to be the body of the rule
	 * @param h  a fact that is going to be the head of the rule
	 * @param or if true the <strong>premisses</strong> are connected by OR, otherwise by AND
	 */
	RuleImpl(List c, Fact h, boolean or) {
		super();
		setBody(c);
		setHead(h);
		prerequisitesConnectedByOr = or;
	}

	/**
	 * Constructor. Pass a single prerequisite and a conclusion.
	 *
	 * @param p a prerequisite
	 * @param h a fact that is going to be the head of the rule
	 * @deprecated use prerequisite instead of fact
	 */
	private RuleImpl(Fact p, Fact h) {
		super();
		body.add(p);
		setHead(h);
	}

	/**
	 * Constructor. Pass a single prerequisite and a conclusion.
	 *
	 * @param p a prerequisite
	 * @param h a fact that is going to be the head of the rule
	 */
	private RuleImpl(Prerequisite p, Fact h) {
		super();
		body.add(p);
		setHead(h);
	}

	/**
	 * Add a fact to the body.
	 *
	 * @param f a fact
	 * @deprecated - rules use now prerequisites instead of facts in the body
	 */
	public void addToBody(Fact f) {
		cachedToString = null;
		body.add(f);
	}

	/**
	 * Apply a set of replacements to a clause. Returns a new clause!
	 *
	 * @param r a collection of replacements
	 * @return the rule (clause) resulting from the application of the replacements
	 */
	public Clause apply(Collection r) {
		return applyToRule(r);
	}

	/**
	 * Apply a single replacement to a fact. Returns a new clause!
	 *
	 * @param r the replacement
	 * @return the rule (clause) resulting from the application of the replacemen
	 */
	public Clause apply(Replacement r) {
		return applyToRule(r);
	}

	/**
	 * Apply a set of substitutions.
	 *
	 * @param r a collection of replacements
	 * @return the rule that is the result of applying the replacements
	 */
	public Rule applyToRule(Collection r) {
		cachedToString = null;
		Vector newBody = new Vector(getBody().size());

		for (Iterator it = getBody().iterator(); it.hasNext();) {
			newBody.add(((Fact) it.next()).apply(r));
		}

		Rule rule = new RuleImpl(newBody, (Fact) getHead().apply(r));
		rule.setBodyOrConnected(isBodyOrConnected());
		return rule;
	}

	/**
	 * Apply a replacement to a rule.
	 *
	 * @param r a replacement
	 * @return the rule that is the result of applying the replacement
	 */
	public Rule applyToRule(Replacement r) {
		cachedToString = null;
		RuleImpl rule =
				new RuleImpl(new Vector(getBody().size()),
						getHead().applyToFact(r));

		for (Iterator it = getBody().iterator(); it.hasNext();) {
			rule.getBody().add(((Fact) it.next()).applyToFact(r));
		}

		rule.setBodyOrConnected(isBodyOrConnected());
		return rule;
	}

	/**
	 * Whether the head contains variables
	 *
	 * @return boolean
	 */
	public boolean isBound() {
		return isBound;
	}

	/**
	 * Get a clause iterator.
	 *
	 * @return a clause iterator
	 */
	public org.mandarax.util.ClauseIterator clauses() {
		if (prerequisitesConnectedByOr) {
			ArrayList rules = new ArrayList(body.size());
			RuleImpl rule = null;

			for (Iterator it = body.iterator(); it.hasNext();) {
				rule = new RuleImpl((Fact) it.next(), head);
				rule.container = this;

				rules.add(rule);
			}

			return new SingleClauseSetIterator(rules);
		} else {
			return new org.mandarax.util.SingleClauseIterator(this);
		}
	}

	/**
	 * Handle a clause set change event.
	 *
	 * @param e an event
	 */
	public void clauseSetChanged(ClauseSetChangeEvent e) {

		// forward key changed events coming from the head
		if ((e.getType() == ClauseSetChangeEvent.KEY_CHANGED) && (e.getSource() == head)) {
			fireClauseSetChangeEvent(new ClauseSetChangeEvent(this,
					e.getOldValue(), e.getNewValue(), ClauseSetChangeEvent.KEY_CHANGED));
		}
	}

	/**
	 * Check whether objects are equal.
	 *
	 * @param obj the object to compare this object with
	 * @return true if the objects are equal, false otherwise
	 */
	public boolean equals(Object obj) {
		if ((obj != null) && (obj instanceof RuleImpl)) {
			RuleImpl r = (RuleImpl) obj;
			boolean result = this.isBodyOrConnected() == r.isBodyOrConnected();
			result = result && ((head == null)
					? r.head == null
					: head.equals(r.head));

			if (result) {
				if (body == null) {
					result = r.body == null;
				} else {
					if (body.size() != r.body.size()) {
						return false;
					} else {
						for (int i = 0; i < body.size(); i++) {
							result = result
									&& body.get(i).equals(r.body.get(i));

							if (!result) {
								return false;
							}
						}
					}
				}
			}

			return result;
		}

		return false;
	}

	/**
	 * Get the body of the rule.
	 *
	 * @return the body (a list of facts)
	 */
	public List getBody() {
		return body;
	}

	/**
	 * Get the head fact.
	 *
	 * @return the hhead of the rule
	 */
	public Fact getHead() {
		return head;
	}

	/**
	 * Get a key for fast access.
	 *
	 * @return the key object
	 * @see org.mandarax.kernel.Fact
	 */
	public Object getKey() {
		return getHead().getPredicate();
	}

	/**
	 * Get the negative literals.
	 *
	 * @return the body of the rule
	 */
	public List getNegativeLiterals() {
		return body;
	}

	/**
	 * Get the positive literals.
	 *
	 * @return a list containing only the head of the rule
	 */
	public synchronized List getPositiveLiterals() {
		if (posLiterals == null) {
			posLiterals = new ArrayList(1);
			posLiterals.add(head);
		}

		return posLiterals;
	}

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

	/**
	 * Indicates whether the clause is atomic.
	 *
	 * @return a boolean
	 */
	public boolean isAtomic() {
		return !prerequisitesConnectedByOr;
	}

	/**
	 * Indicates whether the premisses in the body are connected by OR.
	 *
	 * @return a boolean
	 */
	public boolean isBodyOrConnected() {
		return prerequisitesConnectedByOr;
	}

	/**
	 * Indicates whether the clause is the empty clause.
	 *
	 * @return true if head and body are empty, false otherwise
	 */
	public boolean isEmpty() {
		return getPositiveLiterals().isEmpty() && getNegativeLiterals().isEmpty();
	}

	/**
	 * Indicates whether the object (usually a term or a clause set) can be performed
	 * using the java semantics.
	 *
	 * @return a boolean
	 */
	public boolean isExecutable() {
		return body.isEmpty() && head.isExecutable();
	}

	/**
	 * Remove a fact from the body.
	 *
	 * @param f a fact
	 * @return boolean - indicates whether the element has been found or not
	 * @deprecated - rules use now prerequisites instead of facts in the body
	 */
	public boolean removeFromBody(Fact f) {
		cachedToString = null;
		return body.remove(f);
	}

	/**
	 * Indicate whether two facts share the same key.
	 *
	 * @param f1 the first fact
	 * @param f2 the second fact
	 * @return true if both facts have the same key
	 */
	private boolean sameKey(Fact f1, Fact f2) {
		Predicate p1 = (f1 == null)
				? null
				: f1.getPredicate();
		Predicate p2 = (f2 == null)
				? null
				: f2.getPredicate();

		return (p1 == null)
				? p2 == null
				: (p1.equals(p2));
	}

	/**
	 * Set the body.
	 *
	 * @param b the new body
	 */
	public void setBody(List b) {
		cachedToString = null;
		body = b;
	}

	/**
	 * Set a new value. A value true means that the prerequisistes are connected by OR,
	 * a value false means that the prerequistes are connected by AND.
	 *
	 * @param value a boolean
	 */
	public void setBodyOrConnected(boolean value) {
		cachedToString = null;
		if (prerequisitesConnectedByOr != value) {
			boolean oldValue = prerequisitesConnectedByOr;
			prerequisitesConnectedByOr = value;
			fireClauseSetChangeEvent(new ClauseSetChangeEvent(this, Boolean.valueOf(oldValue), Boolean.valueOf(value), ClauseSetChangeEvent.OTHER));
		}
	}

	/**
	 * Set the head. Note that we fire an event because changing the head
	 * could imply changing the key and containers (knowledge bases) need to be notified
	 * about this.
	 * Prova: add isBound processing
	 *
	 * @param f the new head
	 */
	public void setHead(Fact f) {
		cachedToString = null;
		Fact oldHead = head;

		if (oldHead != null) {
			oldHead.removeClauseSetChangeListener(this);
		}

		head = f;
		isBound = head.isBound();

		// add this as clause set change listener in order to
		// forward key change events

		if (f != null) {
			f.addClauseSetChangeListener(this);
		}

		// the key has changed
		if (!sameKey(oldHead, f)) {
			fireClauseSetChangeEvent(new ClauseSetChangeEvent(this,
					(oldHead == null) ? null : oldHead.getKey(),
					(f == null) ? null : f.getKey(),
					ClauseSetChangeEvent.KEY_CHANGED));
		}

	}

	/**
	 * 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);
			buf.append(" ");
			boolean first = true;
			for (Iterator it = getBody().iterator(); it.hasNext();) {
				if (first) {
					first = false;
				} else {
					buf.append(" ");
					buf.append(prerequisitesConnectedByOr
							? OR
							: AND);
					buf.append(" ");
				}
				buf.append(it.next().toString());
			}
			buf.append(" ");
			buf.append(THEN);
			buf.append(" ");
			buf.append(getHead().toString());
			cachedToString = new String(buf);
		}
		return cachedToString;
	}

	/**
	 * Get an iterator iterating over the predicates contained in this clause set.
	 *
	 * @return an iterator
	 */
	public Iterator predicates() {
		List chain = new ArrayList();
		chain.add(head.predicates());
		for (int i = 0; i < body.size(); i++) {
			chain.add(((ClauseSet) body.get(i)).predicates());
		}
		return new IteratorChain(chain);
	}
}
