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.*;

import org.apache.commons.collections.iterators.FilterIterator;
import org.apache.commons.collections.iterators.IteratorChain;
import org.mandarax.kernel.*;
import org.mandarax.util.logging.*;

/**
 * Abstract super class for knowledge bases. Includes some support methods for event handling.
 * <br>
 * Queries are organized in a Hashtable. 
 * @author <A HREF="mailto:mandarax@jbdietrich.com">Jens Dietrich</A>
 * @version 3.3.1 <9 August 2004>
 * @since 1.2
 */
public abstract class AbstractKnowledgeBase implements org.mandarax.kernel.KnowledgeBase, LogCategories {

	// event listener
	private transient Vector knowledgeBaseListener = new Vector ();
	private List queries = new Vector();

	/**
	 * Constructor.
	 */
	public AbstractKnowledgeBase() {
		super ();
	}
	/**
	 * Add a knowledge base change listener.
	 * @param l org.mandarax.kernel.KnowledgeBaseChangeListener
	 */
	public void addKnowledgeBaseChangeListener(KnowledgeBaseChangeListener l) {
		knowledgeBaseListener.add (l);

		if(LOG_KB_EVENT.isDebugEnabled ()) {
			LOG_KB_EVENT.debug ("Add knowledge base change listener "+ ((l == null)
								   ? "null"
								   : l.toString ()) + " to knowledge base " + toString ());
		}
	}
	/**
	 * Fire a knowledge base change event.
	 * @see KnowledgeBaseChangeEvent
	 * @param state should be one of the constant defined in KnowledgeBaseEvent
	 */
	protected void fireKnowledgeBaseChanged(int state) {
		fireKnowledgeBaseChanged (new KnowledgeBaseChangeEvent (this, state));
	}
	/**
	 * Fire a knowledge base change event.
	 * @see KnowledgeBaseChangeEvent
	 * @param state should be one of the constant defined in KnowledgeBaseEvent
	 * @param changed the affected clause set
	 */
	protected void fireKnowledgeBaseChanged(int state, Object changed) {
		fireKnowledgeBaseChanged (new KnowledgeBaseChangeEvent (this, state,
				changed));
	}
	/**
	 * Fire a knowledge base changed event.
	 * @see KnowledgeBaseChangeEvent
	 * @param state should be one of the constant defined in KnowledgeBaseEvent
	 * @param changed the collection of affected clause sets
	 */
	protected void fireKnowledgeBaseChanged(int state, Collection changed) {
		fireKnowledgeBaseChanged (new KnowledgeBaseChangeEvent (this, state,
				changed));
	}
	/**
	 * Fire a knowledge base change event.
	 * @param e the event
	 */
	protected void fireKnowledgeBaseChanged(KnowledgeBaseChangeEvent e) {
		if((knowledgeBaseListener == null) || (e == null)) {
			return;
		}

		for(Iterator it =
				knowledgeBaseListener.iterator (); it.hasNext (); ) {
			((KnowledgeBaseChangeListener) it.next ()).knowledgeBaseChanged (
				e);
		}
	}
	/**
	 * Remove a knowledge base change listener.
	 * @param l a listener
	 */
	public void removeKnowledgeBaseChangeListener(
			KnowledgeBaseChangeListener l) {
		knowledgeBaseListener.remove (l);

		if(LOG_KB_EVENT.isDebugEnabled ()) {
			LOG_KB_EVENT.debug ("Remove knowledge base change listener "
								+ ((l == null)
								   ? "null"
								   : l.toString ()) + " from knowledge base "
													+ toString ());
		}
	}
	/**
     * Add a query. If a query with the name name already exists, replace it.
     * @param q a query
     */
    public void addQuery(Query q) {
    	synchronized (queries) {
	    	String name = q.getName();
	    	if (name==null) throw new IllegalArgumentException("Queries must have a name");
	    	for (Iterator iter = queries.iterator();iter.hasNext();) {
	    		Query nextQuery = (Query)iter.next();
	    		if (name.equals(nextQuery.getName())) {
	    			iter.remove();
	    			break;
	    		}
	    	}
	    	queries.add(q);
    	}
    }
    /**
     * Remove a query.
     * @param q a query
     * @return true if the object has been found (true) or not (false)
     */
    public boolean removeQuery(Query q) {
    	synchronized (queries) {
    		return queries.remove(q);
    	}
    	
    }    
    /**
     * Get a query by name or null if there is no query with this name.
     * @param queryName a query name
     * @return a query of null if there is no query registered with this name
     */
    public Query getQuery(String queryName) {
    	synchronized (queries) {
	    	for (int i=0;i<queries.size();i++) {
	    		Query nextQuery = (Query)queries.get(i);
	    		if (nextQuery.getName().equals(queryName)) return nextQuery; 
	    	}
	    	return null;
    	}
    }
    /**
     * Get an iterator for the names of all queries registered.
     * @return an iterator
     */
    public Iterator queryNames() {
    	synchronized (queries) {
	    	List names = new ArrayList(queries.size());
	    	for (int i=0;i<queries.size();i++) {
	    		Query nextQuery = (Query)queries.get(i);
	    		names.add(nextQuery.getName());
	    	}
	    	return names.iterator();
    	}
    }
    /**
     * Get an iterator for all queries registered.
     * The iterator cannot be used to remove elements!
     * @return an iterator
     */
    public Iterator queries() {
    	synchronized (queries) {
    		return Collections.unmodifiableList(queries).iterator();	
    	}
    } 
	/**
	 * Get an iterator for all predicates contained (in any clause set within the kb).
	 * @return an iterator
	 */
	public synchronized Iterator predicates() {
		List chain = new ArrayList();
		List clauseSets = getClauseSets();
		for (int i=0;i<clauseSets.size();i++) chain.add(((ClauseSet)clauseSets.get(i)).predicates());
		return new IteratorChain(chain);
	}
	/**
	 * Get a predicate by name.
	 * Note that there might by more than one predicate in the kb with the same name.
	 * In some cases, this makes sense (e.g. polymorphic predicates such as &lt for different
	 * types), but should be avoided for "custom" predicates (such as SimplePredicates).
	 * In this case, this method should return one predicate. In this case, applications can still use
	 * predicates() in order to find all predicates with a particular name.
	 * @return a predicate or null indicating that the kb does not contain a predicate with this name
	 * @param name a predicate name
	 */
	public synchronized Predicate getPredicate(final String name) {
		Iterator predicates = predicates();
		org.apache.commons.collections.Predicate condition = new org.apache.commons.collections.Predicate() {
			public boolean evaluate(Object obj) {
				return (obj instanceof Predicate) && (name.equals(((Predicate)obj).getName()));
			}
		};
		Iterator filtered = new FilterIterator(predicates,condition);
		if (filtered.hasNext()) {
			return (Predicate)filtered.next();
		}
		return null;
	}
}
