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.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import org.jdom.Element;
import org.mandarax.kernel.LogicFactory;
import org.mandarax.util.comparators.DefaultClauseSetComparator;
import org.mandarax.xkb.XKBException;
/**
 * An adapter class for comparators.
 * @see java.util.Comparator
 * @see org.mandarax.util.comparators.DefaultClauseSetComparator
 * @author <A HREF="mailto:mandarax@jbdietrich.com">Jens Dietrich</A>
 * @version 3.3.1 <9 August 2004>
 * @since 2.2 
 */
public class XMLAdapter4Comparators extends AbstractXMLAdapter {
      public static final String COMPARATOR = "comparator";
      public static final String TYPE = "type";
      public static final String TOP_LEVEL_ORDER = "top_level_order";
      public static final String COMPARATOR4RULES = "comparator_for_rules";
      public static final String COMPARATOR4FACTS = "comparator_for_facts";
      public static final String COMPARATOR4SQL_CLAUSE_SETS = "comparator_for_sql_clausesets";
      public static final String COMPARATOR4OTHERS = "comparator_for_others";
      public static final String SEPARATOR = ",";

/**
 * 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,Comparator.class);
      Element e = new Element(COMPARATOR);
      // add class name
      e.setAttribute(TYPE,obj.getClass().getName());
      
      if (obj instanceof DefaultClauseSetComparator) {
      	DefaultClauseSetComparator comp = (DefaultClauseSetComparator)obj;
      	String[] tlo = comp.getTopLevelOrder();
      	StringBuffer buf = new StringBuffer();
      	for (int i=0;i<tlo.length;i++) {      		
      		if (i>0) buf.append(SEPARATOR);
      		buf.append(tlo[i]);
      	}
      	e.setAttribute(TOP_LEVEL_ORDER,buf.toString());
      	
      	Element child = new Element(COMPARATOR4RULES);
      	e.addContent(child);
      	Comparator[] comparators = comp.getComparators4Rules();
      	for (int i=0;i<comparators.length;i++) child.addContent(exportObject(comparators[i],driver,cache));
      	
      	child = new Element(COMPARATOR4FACTS);
      	e.addContent(child);
      	comparators = comp.getComparators4Facts();
      	for (int i=0;i<comparators.length;i++) child.addContent(exportObject(comparators[i],driver,cache));
      	
      	child = new Element(COMPARATOR4SQL_CLAUSE_SETS);
      	e.addContent(child);
      	comparators = comp.getComparators4SQLClauseSets();
      	for (int i=0;i<comparators.length;i++) child.addContent(exportObject(comparators[i],driver,cache));
      	
      	child = new Element(COMPARATOR4OTHERS);
      	e.addContent(child);
      	comparators = comp.getComparators4Others();
      	for (int i=0;i<comparators.length;i++) child.addContent(exportObject(comparators[i],driver,cache));
      }
      return e;
}
/**
 * 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 import fails
 */
public Object importObject(Element e,GenericDriver driver,Map cache,LogicFactory lfactory) throws XKBException {
       String className = e.getAttributeValue(TYPE);
       try {
              Comparator comp = (Comparator)Class.forName(className).newInstance();
              
              if (comp instanceof DefaultClauseSetComparator) {
              	DefaultClauseSetComparator defComp = (DefaultClauseSetComparator)comp;
              	
              	// top level order
              	String tloAsString = e.getAttributeValue(TOP_LEVEL_ORDER);
              	if (tloAsString!=null) {
              		StringTokenizer tokenizer = new StringTokenizer(tloAsString,SEPARATOR);
              		int s = tokenizer.countTokens();
              		String[] tokens = new String[s];
              		for (int i=0;i<s;i++) tokens[i] = tokenizer.nextToken().trim();
              		defComp.setTopLevelOrder(tokens);              		
              	}              	
              	
              	// comparators for categories
              	Comparator[] comparators = null;
              	List children = null;
              	Element child = null;
              	
              	child = e.getChild(COMPARATOR4FACTS);
              	if (child!=null) {
	              	children = child.getChildren(COMPARATOR);
	              	comparators = new Comparator[children.size()];
	              	for (int i=0;i<comparators.length;i++) comparators[i] = (Comparator)importObject((Element)children.get(i),driver,cache,lfactory);
	            }
	            else comparators = new Comparator[0];	            
              	defComp.setComparators4Facts(comparators);
              	
              	child = e.getChild(COMPARATOR4RULES);
              	if (child!=null) {
	              	children = child.getChildren(COMPARATOR);
	              	comparators = new Comparator[children.size()];
	              	for (int i=0;i<comparators.length;i++) comparators[i] = (Comparator)importObject((Element)children.get(i),driver,cache,lfactory);
	            }
	            else comparators = new Comparator[0];	            
              	defComp.setComparators4Rules(comparators);              	
              	
              	child = e.getChild(COMPARATOR4SQL_CLAUSE_SETS);
              	if (child!=null) {
	              	children = child.getChildren(COMPARATOR);
	              	comparators = new Comparator[children.size()];
	              	for (int i=0;i<comparators.length;i++) comparators[i] = (Comparator)importObject((Element)children.get(i),driver,cache,lfactory);
	            }
	            else comparators = new Comparator[0];	            
              	defComp.setComparators4SQLClauseSets(comparators);
              	
              	child = e.getChild(COMPARATOR4OTHERS);
              	if (child!=null) {
	              	children = child.getChildren(COMPARATOR);
	              	comparators = new Comparator[children.size()];
	              	for (int i=0;i<comparators.length;i++) comparators[i] = (Comparator)importObject((Element)children.get(i),driver,cache,lfactory);
	            }
	            else comparators = new Comparator[0];	            
              	defComp.setComparators4Others(comparators);
              	              	
              }
              return comp;
       }
       catch (ClassNotFoundException x) {
            throw new XKBException("Cannot import class " + className + " - check classpath");
       }
       catch (InstantiationException x) {
            throw new XKBException("Cannot instanciate class " + className);
       }
       catch (IllegalAccessException x) {
            throw new XKBException("Cannot instanciate class " + className);
       }
       catch (ClassCastException x) {
            throw new XKBException("Class " + className + " is not a comparator");
       }
}
/**
 * Get the name of the associated tag (element).
 * @return a string
 */
public String getTagName() {
      return COMPARATOR;
}
/**
 * Get the kind of object the adapter can export/import.
 * @return a string
 */
public String getKindOfObject() {
      return GenericDriver.COMPARATOR;
}
}
