// ConvertRegistry.java
// $Id: ConvertRegistry.java,v 1.2 1997/07/30 14:05:51 ylafon Exp $  
// (c) COPYRIGHT MIT and INRIA, 1997.
// Please first read the full copyright statement in file COPYRIGHT.html

package w3c.tools.resources.converter;

import java.util.*;

public class ConvertRegistry {

  protected static Hashtable Converts = null;
  
  static {
    Converts = new Hashtable(20);
    registerConvert( new ConvertInteger());
    registerConvert( new ConvertLong());
    registerConvert( new ConvertString());
    registerConvert( new ConvertBoolean());
    registerConvert( new ConvertFloat());
    registerConvert( new ConvertDouble());
    registerConvert( new ConvertShort());
    registerConvert( new ConvertByte());
    registerConvert( new ConvertFile());
    registerConvert( new ConvertMimeType());
    registerConvert( new ConvertVector());
    registerConvert( new ConvertStringArray());
    registerConvert( new ConvertObject());
  }

  protected static Convert lookupConverter(Class c) {
    Class initialClass = c;
    Convert converter = null;
    while (c != null) {
      if ((converter = (Convert)Converts.get(c)) != null) {
	converter.setInitialClass(initialClass);
	return converter;
      }
      c = c.getSuperclass();
    }
    return null;
  }

  /**
   * Register a new converter.
   * @param The new converter
   */
  public static void registerConvert(Convert conv) {
    Converts.put(conv.classConverted(),conv);
  }

  public static Object defaultValue(Class C) 
    throws NoSuchConverterException
  {
    Convert Conv = null;
    Conv = lookupConverter(C);
    if (Conv == null) 
      throw new NoSuchConverterException(C.getName());
    return Conv.defaultValue();
  }

  /**
   * Object to String convertion.
   * @param The Object to convert
   * @return The Object converted into String 
   * @exception NoSuchConverterException if no converter exists for
   * this Object.
   */
  public static String toString(Object Obj)
    throws NoSuchConverterException
  {
    Convert Conv = null;
    Conv = lookupConverter(Obj.getClass());
    if (Conv == null) 
      throw new NoSuchConverterException(Obj.getClass().getName());
    return Conv.toString(Obj);
  }

  /**
   * String to Object Conversion.
   * @param The String to convert
   * @return The String converted into Object 
   * @exception NoSuchConverterException if no converter exists for
   * this Object.   
   */
  public static Object toObject(Class C, String S)
    throws NoSuchConverterException
  {
    Convert Conv = null;
    Conv = lookupConverter(C);
    if (Conv == null) 
      throw new NoSuchConverterException(C.getName());
    return Conv.toObject(S);
  }
  
}

