package yi.util.io.output;

import java.io.*;

import yi.util.config.*;
import yi.util.log.*;

public class DOU_Csv extends DOU  implements Configurable{

  private static DOU_Csv m_singleton = null;

  public int LOG_LEVEL = 1;

  protected DOU_Csv() {
    Configuration.configParameters(this);
    FILE_POSTFIX = ".csv";
  }

  public static DOU getSingleton() {
    if (m_singleton == null) m_singleton = new DOU_Csv();
    return m_singleton;
  }

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

    try {
      double[][] data = null;
      if (obj instanceof Csvable) {
        data = ((Csvable)obj).toCsv();
      } else if (obj instanceof double[][]) {
        data = (double[][])obj;
      } else if (obj instanceof double[]) {
        data = new double[1][];
        data[0] = (double[]) obj;
      }
      LogHandler.log(this, LOG_LEVEL, 3, "output csv to: " + name);
      PrintWriter out = new PrintWriter(new FileWriter(name));
      for (int i=0; i<data.length; i++) {
        writeCommaDelimitedLine(out, data[i]);
      }
      out.close();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }

  void writeCommaDelimitedLine(PrintWriter out, double[] data) {
    for (int i=0; i<data.length; i++) {
      if (Double.isNaN(data[i])) out.print('?');
      else out.print(data[i]);
      if (i!=data.length-1) out.print(',');
    }
    out.println();
  }

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