/*
 * Licensed Materials - Property of Rogue Wave Software, Inc. 
 * © Copyright Rogue Wave Software, Inc. 2014, 2017 
 * © Copyright IBM Corp. 2009, 2014
 * © Copyright ILOG 1996, 2009
 * All Rights Reserved.
 *
 * Note to U.S. Government Users Restricted Rights:
 * The Software and Documentation were developed at private expense and
 * are "Commercial Items" as that term is defined at 48 CFR 2.101,
 * consisting of "Commercial Computer Software" and
 * "Commercial Computer Software Documentation", as such terms are
 * used in 48 CFR 12.212 or 48 CFR 227.7202-1 through 227.7202-4,
 * as applicable.
 */
package realtime;

import javax.swing.RepaintManager;

/**
 * A <code>RepaintManager</code> that logs the time spent in drawing operations.
 */
abstract class LogRepaintManager extends RepaintManager {
  boolean logging;
  long elapsed;
  Thread logThread;
  long delay = 500;

  /**
   * Creates a new <code>LogRepaintManager</code>.
   */
  public LogRepaintManager() {
    logThread = new Thread() {
      Override
      public void run() {
        for (;;) {
          startDrawingLog();
          long prev = System.currentTimeMillis();
          try {
            sleep(delay);
          } catch (InterruptedException e) {
            break;
          }
          long drawTime = endDrawingLog();
          long now = System.currentTimeMillis();
          long elapsed = now - prev;
          newLog(elapsed, drawTime);
        }
      }

    };
  }

  /**
   * Invoked when a new measurement is available.
   */
  public abstract void newLog(long elapsed, long drawTime);

  /**
   * Starts the logging thread.
   */
  public void startLog() {
    logThread.start();
  }

  /**
   * Stops the logging thread.
   */
  public void endLog() {
    logThread.interrupt();
  }

  /**
   * Starts logging the drawing time.
   * 
   * @see #paintDirtyRegions
   */
  synchronized void startDrawingLog() {
    logging = true;
    elapsed = 0;
  }

  /**
   * Ends logging the drawing time.
   * 
   * @return The elapsed time spent in drawings.
   * @see #paintDirtyRegions
   */
  synchronized long endDrawingLog() {
    logging = false;
    return elapsed;
  }

  /**
   * Overridden to log the time spent fulfilling the posted drawing requests.
   */
  Override
  public void paintDirtyRegions() {
    long start = System.currentTimeMillis();
    super.paintDirtyRegions();
    if (logging)
      elapsed += System.currentTimeMillis() - start;
  }
}