package BusinessProcess;

import java.text.*;
import java.util.*;

public class PTESTHelper
{
  private static int count = 0;
  private static Date startDate = null;
  private static Date lastDate = null;
  private static Date lastStat = null;
  private static int statSecs = 5;
  private static int idleSecs = 60;
  private static DecimalFormat df = new DecimalFormat("#.00");

  public static synchronized void reset()
  {
    System.out.println("** PTEST PERF: Resetting transaction counter due to idle state!");
    count = 0;
    startDate = null;
    lastDate = null;
    lastStat = null;
  }

  private static void printStats()
  {
    if ((lastDate != null) && (startDate != null) &&
        (lastDate.getTime() != startDate.getTime()))
    {
      //System.out.println("count=" + count);
      //System.out.println("startDate=" + startDate.getTime());
      //System.out.println("endDate=" + lastDate.getTime());
      //System.out.println("diff=" +  ((double)(lastDate.getTime() - startDate.getTime()) / 60000.0));
      System.out.println("** PTEST PERF : Count=[" + count + "] " +
        df.format(
          (double) count / ((double) (lastDate.getTime() - startDate.getTime()) / 60000.0)) +
        " inst/min");
      lastStat = new Date();
    }
  }

  public static synchronized void increment(int incrCount)
  {
    if (count == 0)
    {
      startDate = new Date();
    }
    else
    {
      lastDate = new Date();
    }

    count = count + incrCount;

    ////////////////////////////////////
    // initialize last stat date/time //
    ////////////////////////////////////
    if (lastStat == null)
    {
      lastStat = startDate;
    }

    ////////////////////////
    // reset stat if idle //
    ////////////////////////
    if (((double)(System.currentTimeMillis() - lastStat.getTime()) / 1000.0) > idleSecs)
    {
      reset();
    }
    ////////////////////////////////////
    // print stats if determined time //
    ////////////////////////////////////
    else if (((double)(System.currentTimeMillis() - lastStat.getTime()) / 1000.0) > statSecs)
    {
      printStats();
    }
  }

  public static void main(String[] args)
  {
    try
    {
      PTESTHelper.reset();

      for (int i = 1; i <= 10; i++)
      {
        PTESTHelper.increment(i);
        Thread.sleep(15000);
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }
}