package yi.util.io.input;

import java.util.*;
import java.io.*;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.mapping.Mapping;
import yi.util.log.*;
import yi.util.config.*;

public class DIU_Xml extends DIU implements Configurable{
  public String FILE_POSTFIX = ".xml";

  /**
   * Mapping file postfix.  Usually, "xml"
   */
  public String MAPPING_FILE_POSTFIX = "_map.xml";

  public String MAPPING_FILE_DIR = "mappings";

  private static DIU_Xml m_singleton = null;

  public int LOG_LEVEL = 1;

  protected DIU_Xml() {
    Configuration.configParameters(this);
  }

  public static DIU getSingleton() {
    if (m_singleton == null) m_singleton = new DIU_Xml();
    return m_singleton;
  }

  public Object input(String sourceName, String producerName, String dataName, Class c) {
    String name = getInstanceName(sourceName +
                                  ((sourceName.length() > 0)? Character.toString(CONNECT_CHAR) : "") +
                                  producerName +
                                  ((producerName.length() > 0)? Character.toString(CONNECT_CHAR) : "") +
                                  dataName) + FILE_POSTFIX;

    try {
      String mapfile = MAPPING_FILE_DIR + '/' + c.getName() + MAPPING_FILE_POSTFIX;
      LogHandler.log(this, LOG_LEVEL, 3, "Using map file: " + mapfile);
      Mapping map = new Mapping();
      map.loadMapping(mapfile);


      // Create a File to marshal to
      FileReader reader = new FileReader(name);

      // Marshal the person object
      LogHandler.log(this, LOG_LEVEL, 3, "Unmarshal from: " + name);
      Unmarshaller unmarshaller = new Unmarshaller(c);
      unmarshaller.setMapping(map);
      Object obj = unmarshaller.unmarshal(reader);
      reader.close();
      return obj;
    }
    catch (IOException e) {
      System.err.println("Can't find " + name);
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  public String[] getParameterNames() {
    return new String[] {
      "LOG_LEVEL"
    };
  }
}