package org.mandarax.xkb.framework;

/**
 *  Copyright (C) 1999-2004  Jens Dietrich (mailto:mandarax@jbdietrich.com)
 *
 *  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.io.PrintWriter;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.jdom.Comment;
import org.jdom.Element;
import org.mandarax.kernel.ClauseSet;
import org.mandarax.kernel.ExtendedKnowledgeBase;
import org.mandarax.kernel.Fact;
import org.mandarax.kernel.KnowledgeBase;
import org.mandarax.kernel.LogicFactory;
import org.mandarax.kernel.Query;
import org.mandarax.kernel.Rule;
import org.mandarax.sql.SQLClauseSet;
import org.mandarax.xkb.XKBException;
/**
 * An adapter class for knowledge bases. Supports comparators.
 * @see org.mandarax.kernel.KnowledgeBase
 * @author <A HREF="mailto:mandarax@jbdietrich.com">Jens Dietrich</A>
 * @version 3.3.1 <9 August 2004>
 * @since 2.1 
 */

public class XMLAdapter4KnowledgeBases2 extends AbstractXMLAdapter {
      public static final String KNOWLEDGE_BASE = "knowledge_base";

/**
 * Export an object, i.e., convert it to an element in the DOM.
 * @param obj an object
 * @param driver the generic driver
 * @param cache a cache used in order to associate the same
 * id with various occurences of the same object
 * @exception an XKBException is thrown if export fails
 */
public Element exportObject(Object obj,GenericDriver driver,Map cache) throws  XKBException {
      check(obj,KnowledgeBase.class);
      int ftl = driver.getFaultToleranceLevel();
      PrintWriter out = driver.getLogWriter();
      KnowledgeBase kb = (KnowledgeBase)obj;
      Element e = new Element(KNOWLEDGE_BASE);
      List clauseSets = kb.getClauseSets();
      
      // export comparator
      Comparator comp = null;
      if (kb instanceof ExtendedKnowledgeBase && (comp = ((ExtendedKnowledgeBase)kb).getComparator())!=null) {
      			Element eComp = exportObject(comp,GenericDriver.COMPARATOR,driver,cache);
      			e.addContent(eComp);
      }
      
      // export knowledge
      for (Iterator it = clauseSets.iterator();it.hasNext();) {
            ClauseSet cs = (ClauseSet)it.next();
            String kindOfObject = getClauseSetType(cs);
            if (kindOfObject==null)  {
                  String msg = "Cannot figure out what kind of clause set the following object is: " + cs;
                  if (ftl==GenericDriver.LOW_FAULT_TOLERANCE) throw new XKBException(msg);
                  // do nothing if (ftd==driver.HIGH_FAULT_TOLERANCE)
                  else {
                        out.println("Warning");
                        out.println(msg);
                        out.println("The clause is ignored");
                        LOG_XKB.warn(msg);
                        LOG_XKB.warn("The clause is ignored");
                  }
            }
            else {
                  try{
                        Element el = exportObject(cs,kindOfObject,driver,cache);
                        e.addContent(el);
                  }
                  catch (XKBException x) {
                        String msg = "Problems exporting the knowledge base, export failed for " + cs;
                        if (ftl==GenericDriver.LOW_FAULT_TOLERANCE) throw new XKBException(msg);
                        // do nothing if (ftd==driver.HIGH_FAULT_TOLERANCE)
                        else {
                              out.println(msg);
                              out.println("See log for details");
                              e.addContent(new Comment(msg));
                              LOG_XKB.error(msg,x);
                        }
                  }

            }
      }
      // export queries
      for (Iterator it = kb.queryNames();it.hasNext();) {
  		  Query q = kb.getQuery((String)it.next());
	      try{
                Element el = exportObject(q,GenericDriver.QUERY,driver,cache);
                e.addContent(el);
          }
          catch (XKBException x) {
                String msg = "Problems exporting the knowledge base, export failed for query " + q;
                if (ftl==GenericDriver.LOW_FAULT_TOLERANCE) throw new XKBException(msg);
                // do nothing if (ftd==driver.HIGH_FAULT_TOLERANCE)
                else {
                      out.println(msg);
                      out.println("See log for details");
                      e.addContent(new Comment(msg));
                      LOG_XKB.error(msg,x);
                }
          }
      }
      return e;
}
/**
 * Get the type of clause set, e.g. GenericDriver.FACT or GenericDriver.RULE.
 * @param cs a clause set
 * @return a string
 */
protected String getClauseSetType(ClauseSet cs) {
      if (cs instanceof Rule) return GenericDriver.RULE;
      if (cs instanceof Fact) return GenericDriver.FACT;
      if (cs instanceof SQLClauseSet) return GenericDriver.SQL_CLAUSE_SET;
      return null;
}
/**
 * Build an object from an XML element.
 * @param e an element
 * @param driver the generic driver
 * @param cache a cache used to identify objects that have the same id
 * @param lfactory the logic factory used to create objects
 * @exception an XKBException is thrown if export fails
 */
public Object importObject(Element e,GenericDriver driver,Map cache,LogicFactory lfactory) throws XKBException {
       KnowledgeBase kb = new org.mandarax.reference.AdvancedKnowledgeBase();
       int ftl = driver.getFaultToleranceLevel();
       PrintWriter out = driver.getLogWriter();
       List children = e.getChildren();
       for (Iterator it = children.iterator();it.hasNext();) {
            Element child = (Element)it.next();
            
            if (child.getName().equals(GenericDriver.COMPARATOR)) {
            	try {
	                  Object obj = driver.getAdapterByTagName(GenericDriver.COMPARATOR).importObject(child,driver,cache,lfactory);
	                  if (obj !=null) ((ExtendedKnowledgeBase)kb).setComparator((Comparator)obj);
	            }
	            catch (XKBException x) {
	                  String msg = "Problems importing the comparator, root cause: " + x.getMessage();
	                  if (ftl==GenericDriver.LOW_FAULT_TOLERANCE) throw new XKBException(msg);
	                  // do nothing if (ftd==driver.HIGH_FAULT_TOLERANCE)
	                  else {
	                        out.println(msg);
	                        out.println("See log for details");
	                        LOG_XKB.error(msg,x);
	                  }
	            }				
            }
            else {            
	            XMLAdapter adapter = driver.getAdapterByTagName(child.getName());
	            try {
	                  Object obj = adapter.importObject(child,driver,cache,lfactory);
	                  if (obj instanceof ClauseSet) kb.add((ClauseSet)obj);
	                  else if (obj instanceof Query) kb.addQuery((Query)obj);
	                  else throw new XKBException("Can only import clause sets and queries into repository, import for object failed: " + obj);
	            }
	            catch (XKBException x) {
	                  String msg = "Problems importing the knowledge base, root cause: " + x.getMessage();
	                  if (ftl==GenericDriver.LOW_FAULT_TOLERANCE) throw new XKBException(msg);
	                  // do nothing if (ftd==driver.HIGH_FAULT_TOLERANCE)
	                  else {
	                        out.println(msg);
	                        out.println("See log for details");
	                        LOG_XKB.error(msg,x);
	                  }
	            }
            }
       }
       return kb;
}
/**
 * Get the name of the associated tag (element).
 * @return a string
 */
public String getTagName() {
      return KNOWLEDGE_BASE;
}
/**
 * Get the kind of object the adapter can export/import.
 * @return a string
 */
public String getKindOfObject() {
      return GenericDriver.KNOWLEDGE_BASE;
}
}
