package yi.util.io.input;

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

public class DIU_Csv extends DIU implements Configurable{
  public String FILE_POSTFIX = ".csv";

  private static DIU_Csv m_singleton = null;

  public int LOG_LEVEL = 1;

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

  public static DIU getSingleton() {
    if (m_singleton == null) m_singleton = new DIU_Csv();
    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 {
      LogHandler.log(this, LOG_LEVEL, 3, "Read csv from: " + name);


      BufferedReader in = new BufferedReader(new FileReader(name));
      Vector tmp_data = new Vector();
      String line;
      while((line = in.readLine()) != null) {  // Read line, check for end-of-file
        try {
          tmp_data.add(parseCommaDelimitedLine(line));
        } catch (NumberFormatException e) {
//          System.err.println("Can't parse the line.  Ignored: " + line);
        }
      }
      double[][] data = new double[tmp_data.size()][];
      for (int i=0; i<data.length; i++) data[i] = (double[])tmp_data.elementAt(i);
      return data;
    }
    catch (IOException e) {
      System.err.println("Can't find " + name);
    }
    return null;
  }

  double[] parseCommaDelimitedLine(String s) throws NumberFormatException{
    StringTokenizer token = new StringTokenizer(s, ",");
    int data_len = token.countTokens();
    double[] data = new double[data_len];
    int count = 0;
    while (token.hasMoreTokens()) {
      String t = token.nextToken();
      data[count++] = Double.parseDouble(t);
    }
    return data;
  }

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