package brn.sim.data.gantt;

import jist.runtime.JistAPI;

import java.io.IOException;
import java.util.zip.GZIPOutputStream;

/**
 * The actual Gantt trace class. It is bundeled to an output file upon creation
 * and handles TraceEvents during the simulation.
 */
public class GanttTrace extends Trace implements JistAPI.DoNotRewrite {

  private java.io.BufferedWriter m_writer;

  /**
   * Create a new Javis guiTrace object that will write to the file with the
   * supplied name. If the name ends with ".gz", then the output will be written
   * in compressed form (Javis is capable of reading compressed input, NAM
   * isn't, so beware). Compressed output is recommended because guiTrace-files
   * do get big.
   */
  public GanttTrace(String filename) throws IOException {
    super();

    if (filename.endsWith(".gz")) {
      m_writer = new java.io.BufferedWriter(new java.io.OutputStreamWriter(
          new GZIPOutputStream(new java.io.FileOutputStream(filename))));
    } else {
      m_writer = new java.io.BufferedWriter(new java.io.OutputStreamWriter(
          new java.io.FileOutputStream(filename)));
    }
  }

  public synchronized void writePreamble()
      throws IOException {
    // Write a little comment at the beginning
//    m_writer.write("# Trace file generated by Jist/Swans Version " + "1.0.6."
//        + " at " + (new Date()));
//    m_writer.newLine();
  }

  public synchronized void handleEvent(TraceEvent e) throws IOException {
    String s = e.showYourself();

    // System.out.println(s);

    m_writer.write(s);
    m_writer.newLine();

  }

  public synchronized void writePostamble() throws IOException {
    m_writer.close();
  }

  public static Trace createTrace(String fileName) {
    Trace trace = null;

    try {
      trace = new GanttTrace(fileName);
      trace.writePreamble();

    } catch (IOException e) {
      System.out.println("Could not create TraceFile!");
    }

    ShutdownHook.installHook(trace);
    return trace;
  }

  /**
   * Shutdown hook, closes the output file.
   *
   */
  public static class ShutdownHook implements Runnable {
    Trace trace;

    public ShutdownHook(Trace trace) {
      this.trace = trace;
    }

    public void run() {
      try {
        trace.writePostamble();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    public static void installHook(Trace trace) {
      JistAPI.runAt(new ShutdownHook(trace), JistAPI.END);
    }
  }
}
