package org.mandarax.xkb.ruleml;

/*
 * 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.Iterator;
import java.util.List;
import java.util.Vector;

import org.jdom.Element;
import org.mandarax.kernel.ClauseSet;
import org.mandarax.kernel.Fact;
import org.mandarax.kernel.KnowledgeBase;
import org.mandarax.kernel.Query;
import org.mandarax.kernel.Rule;
import org.mandarax.reference.AdvancedKnowledgeBase;
import org.mandarax.xkb.XKBException;

/**
 * Driver implementation for the RULE ML version 0.8.1.
 * New (comp to 0.8) is support for queries. Labels (<_rbaselab> and <_rlab>)
 * are accepted but more or less ignored (mandarax does not support them).
 * Only for queries, the _rlab tag is used to store the common query name.
 * @author <A HREF="mailto:mandarax@jbdietrich.com">Jens Dietrich</A>
 * @version 3.3.1 <9 August 2004>
 * @since 1.9
 */
public class RuleML0_8_1Driver extends AbstractRuleMLDriver {

    // constants for tags and attributes
    public static final String QUERY    = "query";
    public static final String _RBASELAB    = "_rbaselab";
    public static final String _RLAB    = "_rlab";	

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

    /**
     * Export a knowledge base, e.g. convert it into an xml element.
     * @return an element (of the jdom tree)
     * @param kb a knowledge base
     */
    protected Element export(KnowledgeBase kb) {
        Element   e             = new Element (RULEBASE);   
        List      clauseSets    = kb.getClauseSets ();
        ClauseSet nextClauseSet = null;
		// export clause sets
        for (Iterator it = clauseSets.iterator(); it.hasNext (); ) {
            nextClauseSet = (ClauseSet) it.next ();
            if(nextClauseSet instanceof Fact) e.addContent (export ((Fact) nextClauseSet));
            else if (nextClauseSet instanceof Rule) e.addContent (export ((Rule) nextClauseSet));
            else LOG_XKB.warn ("Only facts and rules are suported by driver " + getName () + ", cannot export " + nextClauseSet);
        }  
        // export queries
        for (Iterator iter = kb.queryNames();iter.hasNext();) {
        	String nextQueryName = (String)iter.next();
        	Query nextQuery = kb.getQuery(nextQueryName);
        	e.addContent(export(nextQuery));        	
        }  
        return e;
    }
    /**
     * Get a short text describing the driver.
     * @return a text
     */
    public String getDescription() {
        return "Driver for rulebases as specified by the RULE ML version 0.8.1 specification (incl. query support)";
    }
    /**
     * Get the location (URL) of the associated DTD.
     * @return a text
     */
    public String getDTD() {
        return "http://www.dfki.uni-kl.de/ruleml/dtd/0.81/ruleml-datalog.dtd";
    }

    /**
     * Get the name of the driver.
     * @return a text
     */
    public String getName() {
        return "RuleML 0.8.1";
    }
    /**
     * Import a knowledge base.
     * @return a knowledge base
     * @param e an xml element
     * @throws an XKBException is thrown if import fails
     */
    protected KnowledgeBase importKnowledgeBase(Element e) throws XKBException {

        // since we have no chance to store the class name in this xml format,
        // we choose the default class
        KnowledgeBase kb = new AdvancedKnowledgeBase ();

        // build the clause sets
        List      all    = e.getChildren ();
        Element   next   = null;
        ClauseSet nextCS = null;

        for(Iterator it = all.iterator (); it.hasNext (); ) {
            next = (Element) it.next ();
            if(compare (next.getName (), IMP)) kb.add(importRule(next));
            else if(compare (next.getName (), FACT)) kb.add(importFact(next));
            else if(compare (next.getName (), QUERY)) kb.addQuery(importQuery(next));
            else if(compare (next.getName (), _RBASELAB)) LOG_XKB.warn ("The tag <" + _RBASELAB + "> is not supported by the driver " + this + ", ignore element");
            else LOG_XKB.warn ("Cannot build clause (set) from element <"+ next.getName () + ">..");
        }
        return kb;
    }
    /**
     * Import a query.
     * @return a query
     * @param e an xml element
     * @throws an XKBException is thrown if import fails
     */
    private Query importQuery(Element e) throws XKBException {
        // get body
        Element eBody = e.getChild (_BODY);
        List    body  = null;
        if(eBody == null) {
            LOG_XKB.debug ("No body tag found, assume body is empty");
            body = new Vector ();
        } 
        else {
            body = importBody (eBody);
        }
        // get label
        String name = null;
        Element eName = e.getChild(_RLAB);
        if (eName !=null) {
        	Element eInd = eName.getChild(IND);
        	if (eInd !=null) name = (String)importJavaObject(eInd);
        }
        if (name==null) {
        	LOG_XKB.debug ("No query name found (_rlab tag missing) - use default query name");
        	name = "a query";
        }
        
        // build and return query
        Fact[] facts = new Fact[body.size()];
        for (int i=0;i<body.size();i++) facts[i] = (Fact)body.get(i);
        return lfactory.createQuery(facts,name);
    } 
    /**
     * Export a query.
     * @return an element
     * @param q a query
     */
    private Element export(Query q) {
        Element e1 = new Element(QUERY);
        Element e2   = new Element (_BODY);
        Element e3   = new Element (AND);
        // query facts
        Fact[]    facts = q.getFacts();
        for(int i=0;i<facts.length;i++) {
            e3.addContent (exportFact2Atom (facts[i]));
        }
        e2.addContent (e3);
        e1.addContent (e2);
        // query name
        String name = q.getName();
        if (name!=null && name.trim().length()>0) {
        	Element eName = new Element(_RLAB);
        	Element eName2 = exportJavaObject(name);
        	eName.addContent(eName2);
        	e1.addContent(eName);
        }
        return e1;
    }        
    /**
     * Indicates whether the driver (and the underlying xml format (=dtd))
     * supports auto facts.
     * @return a boolean
     */
    public boolean supportsAutoFacts() {
        return false;
    }
    /**
     * Indicates whether the driver (and the underlying xml format (=dtd))
     * supports clause sets.
     * @return a boolean
     */
    public boolean supportsClauseSets() {
        return false;
    }
    /**
     * Indicates whether the driver (and the underlying xml format (=dtd))
     * supports facts. (some formats might see facts as rules without body)
     * @return a boolean
     */
    public boolean supportsFacts() {
        return true;
    }
    /**
     * Indicates whether the driver (and the underlying xml format (=dtd))
     * supports functions.
     * @return a boolean
     */
    public boolean supportsFunctions() {
        return false;
    }
    /**
     * Indicates whether the driver (and the underlying xml format (=dtd))
     * supports the java semantics (e.g. JFunctions, JPredicate).
     * @return a boolean
     */
    public boolean supportsJavaSemantics() {
        return false;
    }
    /**
     * Indicates whether the driver (and the underlying xml format (=dtd))
     * supports multiple premises.
     * @return a boolean

     */
    public boolean supportsMultiplePremises() {
        return true;
    }
    /**
     * Indicates whether the driver (and the underlying xml format (=dtd))
     * supports multiple premises connected by OR.
     * @return a boolean
     */
    public boolean supportsOrPremises() {
        return false;
    }
    /**
     * Indicates whether the driver (and the underlying xml format (=dtd))
     * supports types.
     * @return a boolean
     */
    public boolean supportsTypes() {
        return false;
    }
    /**
     * Indicates whether the driver (and the underlying xml format (=dtd))
     * supports queries.
     * @return a boolean
     */
    public boolean supportsQueries() {
    	return true;
    }
	/**
	 * Indicates whether the driver (and the underlying xml format (=dtd))
	 * supports negation as failure.
	 * @return a boolean
	 */
	public boolean supportsNegationAsFailure(){
		return false;
	}    
}
