package brn.sim.data;

import jist.swans.Constants;


public class TimeLine extends Line {
  private static final long serialVersionUID = 1L;

  /** ctor for hibernate */
  protected TimeLine() {}

  public TimeLine(String title) {
    super(title);
  }

  public void add(long time, double value) {
    this.add((double) time / (double)Constants.SECOND, value);
  }

  public TimeLine weightedAverage(String title, long interval) {
    TimeLine t = new TimeLine(title);

    double[] time = getX();
    double[] value = getY();

    double ivStart = time[0] - time[0] % interval;
    double ivEnd   = ivStart + interval;

    double start = ivStart;
    double temp = .0;
    for (int i = 1; i < getLengthInternal(); i++) {
      if (time[i] <= ivEnd) {
        temp += value[i-1] * (time[i] - start);
        start = time[i];
      }
      else {
        temp += value[i-1] * (ivEnd - start);
        t.add(ivStart, temp / interval);

        // Skip all intervals where no data is available and go directly to
        // the next interesting interval
        ivStart = time[i] - time[i] % interval;
        if (ivStart > ivEnd) {
          t.add(ivEnd, value[i-1]);
          if (ivStart-interval > ivEnd)
            t.add(ivStart-interval, value[i-1]);
        }
        ivEnd = ivStart + interval;
        temp = value[i-1] * (time[i] - ivStart);
        start = time[i];
      }
    }

    return t;
  }

}
